I have a following code which should return those lat,long in mongodb which are near the ones I mentioned. But the problem is that it returns all the lat,longs.
$collection->ensureIndex(array("location" => "2d"));
$a=array(24.8934,67.0281);
//print_r($a);
$distance='500';
$query = array('location' => array('$near' => array(24.8934,67.0281)));
$cursor = $collection->find($query);
try{
if ($cursor) {
echo $arr= json_encode(iterator_to_array($cursor));
// $j= json_decode($arr,false);
echo var_dump(json_decode($arr));
$j = json_decode($arr,false);
$lat= $j->{'57237036d89c45e1e3fda94e'}->location[0];
$lng= $j->{'57237036d89c45e1e3fda94e'}->location[1];
} else {
echo "{ 'status' : 'false' }";
}
It returns the following:
object(stdClass)[7]
public '572453d55addfab49090ea71' =>
object(stdClass)[6]
public '_id' =>
object(stdClass)[8]
public '$id' => string '572453d55addfab49090ea71' (length=24)
public 'location' =>
array (size=2)
0 => float 24.8615
1 => float 67.0099
public '57237036d89c45e1e3fda94e' =>
object(stdClass)[9]
public '_id' =>
object(stdClass)[10]
public '$id' => string '57237036d89c45e1e3fda94e' (length=24)
public 'location' =>
array (size=2)
0 => float 33.7715
1 => float 72.7511
Instead it should only return first document.
The reason that the sample code is not working correctly is that the $distance variable is defined, but it is not being passed to the query.
You would need to modify your code to be similar to the following example:
$distance=500;
$cursor = $collection->find(['location' =>
['$near'=> [ 24.8934,67.0281 ],
'$maxDistance' => $distance]]);
For most use cases, we recommend that you should be using the newer 2dsphere index which uses earth-like geometry and GeoJSON objects. Please review 2dsphere index for more information on this functionality.
If you use a 2dsphere index, the code would be similar to this:
$distance=500;
$cursor = $collection->find(['location' =>
['$near'=>
['$geometry'=>
[ 'type' => "Point", 'coordinates' => [ 24.8934,67.0281 ] ],
'$maxDistance' => $distance]]]);
You may also find the spherical geometry tutorial helpful.