实际开发中,常常需要获取用户附近的商家,思路是
- 获取用户位置(经纬度信息)
- 在数据库中查询在距离范围内的商家
注: 本文章内计算距离所使用地球半径统一为 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公里范围之内的。因为我的数据库里面只添加了连个测试商家,大家将就看一下,理解了就行了。
到此这篇关于php/laravel通过经纬度计算距离获取附近商家的文章就介绍到这了,更多相关php经纬度距离计算内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论