Geolocation: Getting Distance in Miles with PHP & MongoDB
Geolocation requirements are becoming very common with all the location based apps cropping up recently and MongoDB provides some great features to get up and running quickly.
By default Mongo returns results in radians, in order to get the distance in the miles you need to divide the radius distance by the radius of the earth.
Getting All Results Within 5 Miles
$m = new Mongo(); //open a connection to the server $db = $m->myapp //get the myapp database $collection = $db->shops; $collection->ensureIndex(array('geo_coords' => '2d')); $lat = 37.0625; $lng = -95.677068; $radiusMiles = 5; //get all results within 5 miles $radiusOfEarth = 3956; //avg radius of earth in miles $result = $collection->find( array('geo_coords' => array('$within' => array('$centerSphere' => array( array($lng, $lat), $radiusMiles/$radiusOfEarth ) ) ) ) );
This code requires v1.7+