简体   繁体   中英

Calculate bounding box based on given coordinates and distance/radius

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM