圆形内的坐标(圆心与半径组成的圆形范围,返回距圆心距离)
$juli = getDistance($loc1[1], $loc1[0], $loc2[1], $loc2[0]); $pipeline[] = ['$geoNear' => [ 'near'=>$loc1, // 当前坐标 'spherical'=>true, // 计算球面距离 'distanceMultiplier'=>6378137, // 地球半径,单位是米,那么的除的记录也是米 'maxDistance'=>($juli+1)/6378137, // 过滤条件200000米内,需要弧度 'distanceField'=>'distance' ]]; $pipeline[] = ['$project' => ['_id' => 1, 'uid' => 1, 'loc' => 1, 'state' => 1, 'close' => 1, 'hezuo_type' => 1, 'distance' => 1]]; $pipeline[] = ['$match' => ['state' => ['$in' => [1, -2, 0]]]]; $pipeline[] = ['$limit' => 3]; $result = $db->aggregate(COLLECTION_USERCOMPANY_SET, $pipeline); echo json_encode($result);
圆形内的坐标(圆心与半径组成的圆形范围,不返回距圆)
$loc1 = [112.53362699029492, 33.01046814237027]; // 我的位置 $loc2 = [112.53385881284048,33.001754496370701]; // 最远的位置 $maxDistance = sqrt(pow($loc2[0] -$loc1[0], 2) + pow($loc2[1] -$loc1[1], 2)); echo $maxDistance; $filter_store['loc'] = ['$near' => $loc1, '$maxDistance' => $maxDistance]; $projection = ['_id' => 1, 'uid' => 1, 'loc' => 1, 'state' => 1, 'close' => 1, 'hezuo_type' => 1]; $result = $db->find(COLLECTION_USERCOMPANY_SET, $filter_store, [], $projection); echo json_encode($result);
计算距离
function getDistance($lat1, $lng1, $lat2, $lng2) { // define('PI',3.1415926535898); $pi = 3.1415926535898; //define('EARTH_RADIUS',6378.137); $earth = 6378.137; $radLat1 = $lat1 * ($pi / 180); $radLat2 = $lat2 * ($pi / 180); $a = $radLat1 - $radLat2; $b = ($lng1 * ($pi / 180)) - ($lng2 * ($pi / 180)); $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))); $s = $s * $earth; $s = round($s * 10000) / 10000; return $s * 1000; }
矩形平面内的坐标(左下角位置与右上角位置组成的矩形范围)
$filter['loc'] = ['$within' => ['$box' => [$lb_loc, $rt_loc]]]; $filter['$or'] = [['state' => 1], ['state' => -2]]; // 正常营业与停业中 if (trim($data['search']) !== "") { $filter["company_name"] = array('$regex' => $data["search"]); } $projection = ['_id' => 1, 'uid' => 1, 'company_name' => 1, 'company_logo' => 1, 'loc' => 1, 'company_address' => 1, 'ctype' => 1, 'top_id' => 1, 'state' => 1, 'close' => 1, 'hezuo_type' => 1]; $results = $db->queryPage(COLLECTION_USERCOMPANY_SET, $filter, array("_id" => -1), $data["page"], $data["pagenum"], $projection);
备注:
1、https://github.com/mongodb/mongo-php-driver
2、创建2d索引
$db->createIndex(COLLECTION_USERCOMPANY_SET, ['loc' => '2d'], ['min' => -180 , 'max' => 180, 'bits' => 26 ]);
3、参考:https://blog.csdn.net/zxjiayou1314/article/details/50844489
4、$filter_store['loc'] = ['$within' => ['$box' => [$lb_loc, $rt_loc]]];在旋转地图的情况下,返回的结果不准确。