实际开发中,常常需要获取用户附近的商家,思路是
注: 本文章内计算距离所使用地球半径统一为 6378.138 km
- public function mpa_list($latitude,$longitude,$distance)
- {
- // $latitude = 34.306465;
- // $longitude = 109.050952;
- // $distance = 5;
- //1.计算最大最小经纬度范围
- $range = 180 / pi() * $distance / 6378.138; //搜索 N km 之内
- $lngR = $range / cos($latitude * pi() / 180);
- $maxLat = $latitude + $range; //最大纬度
- $minLat = $latitude - $range; //最小纬度
- $maxLng = $longitude + $lngR; //最大经度
- $minLng = $longitude - $lngR; //最小经度
- //2.查找经纬度符合条件的商家
- $list = Village::select("id","title","longitude","latitude")
- ->whereBetween('latitude', [$minLat, $maxLat])
- ->whereBetween('longitude', [$minLng, $maxLng])
- ->where('status', 1)
- ->get();
- //3.计算距离
- foreach ($list as &$item){
- $item['distance'] = $this->getDistanceBy2Point([$longitude, $latitude], [$item['longitude'], $item['latitude']]);
- }
- if($list){
- $list = $list->toArray();
- }
- //4.排序
- $list = $this->arraySort($list, 'distance');
-
- return $list;
- }
二维数组排序方法
- // 二维数组排序方法
- public static function arraySort($arr, $field, $sort = SORT_ASC){
- $key = array_column($arr, $field);
- array_multisort($key, $sort, $arr);
- return $arr;
- }
根据经纬度计算两点距离
- /**
- * 根据起点坐标和终点坐标测距离
- * @param [array] $from [起点坐标(经纬度),例如:array(118.012951,36.810024)]
- * @param [array] $to [终点坐标(经纬度)]
- * @param [bool] $km 是否以公里为单位 false:米 true:公里(千米)
- * @param [int] $decimal 精度 保留小数位数
- * @return [string] 距离数值
- */
- public static function getDistanceBy2Point($from, $to, $km = true, $decimal = 2){
- sort($from);
- sort($to);
- $EARTH_RADIUS = 6378.138; // 地球半径系数
- $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;
- if($km && $distance > 1000){
- return round($distance / 1000, 2) . 'km';
- }
- return round($distance, $decimal) . 'm';
- }
实际测试:我这边的测试数据比较少,我就用了50公里范围之内的。因为我的数据库里面只添加了连个测试商家,大家将就看一下,理解了就行了。
