PHP,Mysql根据经纬度计算距离并排序
/**
* 接收页面传过来的经纬度,然后筛选出距离最近的商铺
*/
public function CooperativeStoreIn()
{
$data = [
'latitude' => input('latitude'),
'longitude' => input('longitude')
];
// PHP,Mysql根据经纬度计算距离并排序
$sql = "select * from gf_cooperative_store order by ACOS(SIN(('".$data['latitude']."' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(('".$data['latitude']."' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(('".$data['longitude']."' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 asc limit 30";
$shops['datas'] = db('cooperative_store')->query($sql);
$shops['status'] = 1;
// 通过获取客户端经纬度坐标与店铺经纬度坐标计算距离,单位是KM
foreach ($shops['datas'] as $key => $value) {
$lat1 = $data['latitude'];
$lng1 = $data['longitude'];
$lat2 = $value['latitude'];
$lng2 = $value['longitude'];
//将角度转为狐度
$radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
$radLat2=deg2rad($lat2);
$radLng1=deg2rad($lng1);
$radLng2=deg2rad($lng2);
$a=$radLat1-$radLat2;
$b=$radLng1-$radLng2;
$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137; //return $s; 单位是km
$sd = round($s,2); //保留2位小数,四舍五入
array_push($shops['datas'][$key],$sd);
}
// echo db('cooperative_store')->getLastSql();
$shops['datas'] = array_map(function($tag) {
return array(
'distance' => $tag['0'],
'address' => $tag['address'],
'addtime' => $tag['addtime'],
'content' => $tag['content'],
'id' => $tag['id'],
'latitude' => $tag['latitude'],
'longitude' => $tag['longitude'],
'status' => $tag['status'],
'tel' => $tag['tel'],
'thumbnail' => $tag['thumbnail'],
'title' => $tag['title'],
);
}, $shops['datas']);
return json($shops);
}