Skip to content

Instantly share code, notes, and snippets.

@bastianallgeier
Last active April 19, 2020 18:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bastianallgeier/6dcd06f66e23f0d4e2a5 to your computer and use it in GitHub Desktop.
Save bastianallgeier/6dcd06f66e23f0d4e2a5 to your computer and use it in GitHub Desktop.
Radius search
<?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