蒼天家 本家
MongoDB 使用2dsphere 查詢地理位置 2015-11-10
插入資料:
$data = new stdClass();
$data->name = "勤美綠園道";
$data->category = "Dist";
$data->loc->type = "Point";
$data->loc->coordinates = array(120.663816 , 24.151040);
$collection->insert($data);

將坐標資料進行索引化:
$collection->createIndex( array("loc" => "2dsphere" ) );

搜尋指定範圍內的點(圓形):
$lng = 120.663816;
$lat = 24.151040;
$radius = 5;
$radiusOfEarth = 3963.2;
$data = array('loc' =>
array('$geoWithin' =>
array('$centerSphere' =>
array(
array(floatval($lng) , floatval($lat)), $radius / $radiusOfEarth
)
)
)
);
$cursor = $collection->find($data);
$result = iterator_to_array($cursor);

搜尋指定範圍內的點(圓形 , 由近至遠):
$lng = 120.663816;
$lat = 24.151040;
$radius = 5;

$data = new stdClass();
$near = '$near';
$geometry = '$geometry';
$maxDistance = '$maxDistance';
$data->location->$near->$geometry->type = 'Point';
$data->location->$near->$geometry->coordinates = array(floatval($loc['lon']) , floatval($loc['lat']));
$data->location->$near->$geometry->$maxDistance = (int)$loc['radius'];

$cursor = $collection->find($data);
$result = iterator_to_array($cursor);
$collection要先行宣告你所存取的db與collection

參考資料
http://jamesroberts.name/blog/2012/03/12/mongodb-geospatial-query-example-in-php-with-distance-radius-in-miles-and-km/
https://docs.mongodb.org/manual/tutorial/build-a-2dsphere-index/
https://docs.mongodb.org/manual/tutorial/query-a-2dsphere-index/
關於我

隨手用部落格

紀錄平時學習用到的東西

考慮想重改版

Github 自學倉庫

我的 Github 帳號

PHP開發

公司: 原生PHP

個人: Slim -> Flight