Reputation: 35
In a PHP script I have a SPARQL query returning POIs within a given distance of another point. This is the line in the query which handles the geo-filtering:
FILTER (?long > " . ($resource_long - $search_radius) . " && ?long < " . ($resource_long + $search_radius) . " && ?lat > " . ($resource_lat - $search_radius) . " && ?lat < " . ($resource_lat + $search_radius) . " )
For now I have been using an integer (the variable $search_radius) to limit my results, and this would translate to degrees. There are, however, two problems with this. Firstly, using degrees as a parameter is not very user friendly, and kilometers would be to prefer. Secondly, the further away from the equator one gets, the narrower the distance gets between two degrees of longitude. This will in turn result in fewer returned results. So, the question is; given a lat/long coordinate, how can I calculate the bounding box based on a given radius/distance in km?
Upvotes: 1
Views: 5554
Reputation: 18550
Use radians for everything
then
$radius = $distance/ 6371.01; //6371.01 is the earth radius in KM
$minLat = $lat - $radius;
$maxLat = $lat + $radius;
$deltaLon = asin(sin($radius) / cos($lat));
$minLon = $lon - $deltaLon;
$maxLon = $lon + $deltaLon;
Then convert back to degrees if needed.
This doesnt work if bounds are crossed. There are classes available to help
https://github.com/anthonymartin/GeoLocation.php
For example
Thats the outer bounds, You can get the inner bounds square by doing multiplying by the $radius by cos(M_PI_4) for top lat, sin(M_PI_4) for top lon, cos(3*M_PI_4) for bottom lat and sin(3*M_PI_4) for bottom Lon
Upvotes: 3