How to query wikidata using SPARQL to find a place that matches certain criteria and is geographically near another city

Viewed 211

I wrote the following SPARQL query to find the wikidata item with the label "San Leucio" in Italy.

SELECT DISTINCT * WHERE {
                        ?location ?label 'San Leucio'@en .  
                        ?location wdt:P17 wd:Q38 .
                        ?location rdfs:label ?locationName .
                        OPTIONAL {
                          ?article schema:about ?location .
                          ?article schema:isPartOf <https://en.wikivoyage.org/> .
                        }
                        ?location wdt:P18 ?image .
                        FILTER(lang(?locationName) = "en") 
                        }

The query returns these 3 results:

wd:Q55179410
wd:Q20009063
wd:Q846499

The result I want is wd:Q846499, which is outside of Naples, Italy. Is there any way I could further filter this query to return the result that is nearest to Naples? I know that I can get the geoCoordinates for each of these with ?location wdt:P625 ?coordinates, but I'm not sure how I could use that to compare to the geo-coordinates of Naples to get what I want.

1 Answers
SELECT DISTINCT * {
    VALUES ?naples {wd:Q2634}
    ?Napfes wdt:P625 ?naples_coordinates.
    ?location rdfs:label 'San Leucio'@en .  
    ?location wdt:P17 wd:Q38 .
    ?location wdt:P18 ?image .
    ?location wdt:P625 ?location_coordinates.
    OPTIONAL {
        ?article schema:about ?location .
        ?article schema:isPartOf <https://en.wikivoyage.org/> .
    }
    BIND (geof:distance(?location_coordinates, ?naples_coordinates) AS ?distance)
} ORDER BY ?distance LIMIT 1
Related