### laravel6+mongo使用
#### 利用经纬度查询附近店铺
1. 方法1 自动计算每个点的距离
```php
//map_geo 为经纬度字段,array类型,2dsphere索引
$data = self::query()->raw(function ($collection) use ($lon,$lat,$maxDistance,$limit) {
$aggregate = [];
$aggregate[]['$geoNear'] = [
'near'=>['type'=>"Point", 'coordinates'=>[$lon,$lat]],
'distanceField'=>'distance',
'includeLocs'=>'map_geo',
'spherical'=> true,
'skip' =>($page-1)*$limit,//跳过的条数
'limit'=>$limit,//查看的条数
'maxDistance' => $maxDistance,
];
//这里还可以继续添加各种条件
return $collection->aggregate($aggregate)->toArray();
});
dd($data);
```
2. 方法二 需要通过经纬度计算距离
```php
//map_geo 为经纬度字段,array类型,2dsphere索引
$allData = self::where('map_geo','near',[
'$geometry'=>[
'type' => 'Point',//固定写法
'coordinates' => [$lon,$lat],
],
'$maxDistance' => $maxDistance,//最大范围米
])->where('is_del',0);
if($industryCategoryId){
$allData = $allData->where(['industry_category'=>(int)$industryCategoryId]);
}
$allData = $allData->select('is_identity_card','last_receive_order_time','assure_credit')
->paginate($limit)->get()->toArray();
```
3. 计算两点间距离的方法
```php
/**
*计算地球表面2点之间的球面距离,返回米数
* @param $lat1
* @param $lon1
* @param $lat2
* @param $lon2
* @param $radius
* @return float
*/
if(! function_exists('distance')){
function distance($lat1, $lon1, $lat2, $lon2, $radius = 6378140)
{
$rad = floatval(M_PI / 180.0);
$lat1 = floatval($lat1) * $rad;
$lon1 = floatval($lon1) * $rad;
$lat2 = floatval($lat2) * $rad;
$lon2 = floatval($lon2) * $rad;
$theta = $lon2 - $lon1;
$dist = acos(sin($lat1) * sin($lat2) +
cos($lat1) * cos($lat2) * cos($theta)
);
if ($dist < 0) {
$dist += M_PI;
}
$dist = ceil($dist * $radius);
return $dist;
}
}
```