根据坐标定位计算距离
2020-02-28 本文已影响0人
苏大发
百度地图api可以根据两地坐标计算距离,文档地址:
http://lbsyun.baidu.com/
php计算方法如下:
/**
* 根据经纬度计算距离
*
*/
public function getDistance($lat1=38.072217, $lng1=114.472661, $lat2=38.016821, $lng2=114.490825)
{
$earthRadius = 6367000; //approximate radius of earth in meters lat1纬度 经度118.91701861624
// print_r($lat2);
// echo "<br>";
// print_r($lng1);
// echo "<br>";
$lat1 = ($lat1 * pi() ) / 180;
$lng1 = ($lng1 * pi() ) / 180;
$lat2 = ($lat2 * pi() ) / 180;
$lng2 = ($lng2 * pi() ) / 180;
$calcLongitude = $lng2 - $lng1;
$calcLatitude = $lat2 - $lat1;
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
// print_r($stepTwo);
$calculatedDistance = $earthRadius * $stepTwo;
// echo "<br>";
// print_r($calculatedDistance);
return round($calculatedDistance);
}
也可以使用SQL直接在查询中根据表中的坐标进行计算传入坐标与表中数据的相距距离
(以 thinkphp 为例)
$info = $this->field('id,name,floor((2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$ypoint.'-ypoint)/360),2)+COS(3.1415926535898*'.$ypoint.'/180)* COS(ypoint * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$xpoint.'-xpoint)/360),2))))*1000) as distance,jobs,avatar,hid,hdid,special,accept,online')
->where("status=1 and is_check=1 ".$where)
->order("distance asc, online desc")
->paginate(6,false,[
'page' => $pageNum,
'var_page' => 'page',
]);
注:纬度latitude
、经度longitude
。