sparqlwikidatawikidata-query-service

Retrieve latitude and longitude of a sample of coordinates from Wikidata using SPARQL


I am trying to retrieve samples of coordinates in Wikidata via SPARQL but am having a very difficult time trying to achieve it. I would want to get only a single pair of coordinates per place and display the result in a column, and the latitude and longitude of the said coordinates sample in their own columns.

The following code (link to WQS) I use below works, but it does not get the coordinates values labels in Point(5.936111111 51.21) format. When I replace p:P625 with wdt:P625, no items are retrieved. Additionally, Borculo (Q1025685) appears twice in the results with two unique coordinates:

SELECT DISTINCT ?place ?placeLabel (SAMPLE(?temp1) AS ?coords_sample) ?lat ?long {

  ?place p:P31 ?instanceOf.
  ?instanceOf ps:P31/wdt:279* wd:Q2039348.
  
  ?place p:P625 ?temp1.
  ?temp1 psv:P625 ?temp2.
  ?temp2 wikibase:geoLatitude ?lat.
  ?temp2 wikibase:geoLongitude ?long. 

  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
} GROUP BY ?place ?placeLabel ?lat ?long

ORDER BY ?placeLabel

Solution

  • Use ps:P625 for obtaining the coordinates in the desired format (see also the manual on Wikibooks).

    Also, it is not sufficient to sample the coordinates statement if you also group by ?lat and ?long. Hence, you'd better to sample it in a subquery.

    Final result:

    SELECT DISTINCT ?place ?placeLabel ?coords ?lat ?long {
      ?place p:P31/ps:P31/wdt:279* wd:Q2039348 ;
             p:P625 ?coords_sample .
      {
        SELECT (SAMPLE(?coords_stmt) AS ?coords_sample) {
          ?place p:P31/ps:P31/wdt:279* wd:Q2039348 ;
                 p:P625 ?coords_stmt .
        } GROUP BY ?place
      }
      ?coords_sample ps:P625 ?coords;
                     psv:P625 [
                       wikibase:geoLatitude ?lat;
                       wikibase:geoLongitude ?long
                     ] .
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    ORDER BY ?placeLabel