-
-
Save jonabaptistella/618ed19a520ee96340260eeaeba6e7a7 to your computer and use it in GitHub Desktop.
Radius search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Simple helper to fetch the bounding boxes | |
| * for a point on the map (lat,lng) by radius. | |
| * | |
| * @param double $lat Latitude | |
| * @param double $lng Longitude | |
| * @param int $radius Radius in km | |
| * @return array | |
| */ | |
| function getBoundingBox($lat, $lng, $radius) { | |
| $earthRadius = 6371; | |
| $maxLat = $lat + rad2deg($radius / $earthRadius); | |
| $minLat = $lat - rad2deg($radius / $earthRadius); | |
| $maxLng = $lng + rad2deg($radius / $earthRadius/cos(deg2rad($lat))); | |
| $minLng = $lng - rad2deg($radius / $earthRadius/cos(deg2rad($lat))); | |
| return array( | |
| 'minLat' => $minLat, | |
| 'maxLat' => $maxLat, | |
| 'minLng' => $minLng, | |
| 'maxLng' => $maxLng, | |
| 'center' => array('lat' => $lat, 'lng' => $lng), | |
| 'nw' => array('lat' => $maxLat, 'lng' => $minLng), | |
| 'ne' => array('lat' => $maxLat, 'lng' => $maxLng), | |
| 'sw' => array('lat' => $minLat, 'lng' => $minLng), | |
| 'se' => array('lat' => $minLat, 'lng' => $maxLng), | |
| ); | |
| } | |
| // search in all visible children of the current page | |
| // each subpage must have a lat (Latitude) field and a lng (Longitude) field | |
| // in order to make the search work. | |
| $entries = $page->children()->visible(); | |
| // set the desired radius | |
| $radius = 25; // 25 km | |
| // get the min and max lat and the min and max lng | |
| $coords = getBoundingBox($lat = 49.5004256, $lng = 8.5020751, $radius); | |
| // filter entries with a custom filter | |
| $entries = $entries->filter(function($retailer) use($coords) { | |
| if(doubleval($retailer->lat()->value) >= $coords['minLat'] and | |
| doubleval($retailer->lat()->value) <= $coords['maxLat'] and | |
| doubleval($retailer->lng()->value) >= $coords['minLng'] and | |
| doubleval($retailer->lng()->value) <= $coords['maxLng']) { | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| }); | |
| // do something with the filtered entries here. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment