Yii2 通过经纬度计算距离

在线计算工具:

  • http://tool.yovisun.com/longlat/index.php
  • http://www.ab126.com/Geography/1884.html

参考文档:

  • https://blog.csdn.net/shenxian1021/article/details/80577718
  • https://www.cnblogs.com/caichenghui/p/5977431.html
  • https://www.jb51.net/article/153766.htm

方案一

/**
 * 求两个已知经纬度之间的距离,单位为米
 * @param $lng1, $lng2 经度
 * @param $lat1, $lat2 纬度
 * @return float 距离,单位米
 */
function getdistance($lng1, $lat1, $lng2, $lat2) {
    $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.138 * 1000;
    return $s;
}

方案二

/*
 * 1.纬度1,经度1,纬度2,经度2
 * 2.返回结果是单位是KM
 * 3.保留一位小数
 */
function getDistance($lat1,$lng1,$lat2,$lng2)
{
    $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)))*6371;
    return round($s,1);
}

SQL 解决方案

/**
 * $longitude 经度
 * $latitude  纬度
 */
'(1000*6378.138 * 2 * ASIN(SQRT(POW(SIN((' . $latitude . ' * PI() / 180 - latitude * PI() / 180) / 2), 2) + COS(' . $latitude . ' * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN(( ' . $longitude . ' * PI() / 180 - longitude * PI() / 180 ) / 2),2))))'

SELECT *, (1000 * 6378.138 * 2 * ASIN(SQRT(POW( SIN(( 0 * PI() / 180 - latitude * PI() / 180 ) / 2 ), 2 ) + COS( 0 * PI() / 180 ) * COS( latitude * PI() / 180 ) * POW( SIN(( 0 * PI() / 180 - longitude * PI() / 180 ) / 2 ), 2 )))) AS `dis` FROM `e_hotel` ORDER BY `dis`

测试

起点经纬度: 0, 0
重点经纬度: 120.2777722300, 31.4791885800

方案计算结果:
    看方案一: 12853725.254591906 M
    看方案二: 12839.340195681725 KM
    网上方案: 12838.722483866 KM