使用mongodb和php查找最近的餐厅位置

使用mongodb和php查找最近的餐厅位置,php,mongodb,google-maps,Php,Mongodb,Google Maps,我在MongoDB有一个叫餐馆的收藏 { "_id" : ObjectId("5281f8d660ad39040c000001"), "name" : "Bucksters Coffee", "serves" : "Fast Food", "location" : [ "23.755339", "90.375408" ] } { "_id

我在MongoDB有一个叫餐馆的收藏

   {
       "_id" : ObjectId("5281f8d660ad39040c000001"),
       "name" : "Bucksters Coffee",
       "serves" : "Fast Food",
       "location" : [ 
          "23.755339", 
          "90.375408"
       ]
    }    
    {
        "_id" : ObjectId("5285cf0860ad39380b000000"),
        "name" : "A1 Donuts",
        "serves" : "Fast Food",
        "location" : [ 
            "18.5087016", 
            "73.8124984"
        ]
    }
    {
        "_id" : ObjectId("5285cf3f60ad39380b000002"),
        "name" : "B1 Donuts",
        "serves" : "Fast Food",
        "location" : [ 
            "18.4893148", 
            "73.8213213"
        ]
    }
    {
        "_id" : ObjectId("5285e7a260ad39380b000009"),
        "name" : "C1 Donuts",
        "serves" : "Fast Food",
        "location" : [ 
            "18.5308225", 
            "73.8474647"
        ]
    }
我的位置是[“18.5170345”,“73.83476”],我想找到离我位置最近的餐馆,大约5公里

所以我试着做以下事情

对于插入式餐馆

<?php
try {

   $conn = new Mongo('localhost');

  // access database
  $db = $conn->demo;

  // access collection
  $collection = $db->restaurants;

  $forlatadd="shivaji nagar, pune";

  //for lat& Long
$prepAddr = str_replace(' ','+',$forlatadd);

$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');

$output= json_decode($geocode);

$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;


  $a=array("$lat","$long");
  //print_r($a);
   $document = array( "name" => "C1 Donuts","serves" => "Fast Food","location" =>$a);

  $collection->insert($document);

    $collection->ensureIndex(array("location" => "2d"));


  // disconnect from server
  $conn->close();
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());
}
?>
但我已经做了

$collection->ensureIndex(array("location" => "2d"));
在集合中插入新餐厅时,
请帮助我从我的位置查找最近的餐厅。

在mongodb文档中,他们在位置定义中指定了顺序,事实上,我在以前的开发中遇到了订单问题:

重要提示:按以下顺序指定坐标:“经度,纬度。”

它对我有用

只有改变

$a=array("$lat","$long");  //It takes lat & long as string


它的工作原理是

我用“经度,纬度”来表示,但如果我输入距离2公里,它也会给出总数据。你重建了2d索引吗?是的,但对于距离2k,我可以在查询中写什么。
$collection->ensureIndex(array("location" => "2d"));
$a=array("$lat","$long");  //It takes lat & long as string
$a=array($long,$lat);  //It takes lat&long as float.