PHP开发小技巧①③—PHP根据两点间的经纬度计算距离

时间:2023-01-08 19:43:30

        这个在我们开发过程中也是经常用到的,大家直接读代码吧:

    <?php
/**
* =======================================
* Created by Zhihua_W.
* Author: Zhihua_W
* Date: 2017/5/24 0024
* Time: 上午 10:36
* Project: PHP开发小技巧
* Power: 根据两点间的经纬度计算距离
* =======================================
*/


echo GetDistance(31.2014966, 121.40233369999998, 31.22323799999999, 121.44552099999998);

/**
* @desc 根据两点间的经纬度计算距离
* @param float $lat 纬度值
* @param float $lng 经度值
* @return float
*/
function GetDistance($lng1, $lat1, $lng2, $lat2)
{
//方法1
//地球半径
$earthRadius = 6367000;
$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)));
$calculatedDistance = $earthRadius * $stepTwo;
return round($calculatedDistance);

//方法2
//将角度转为狐度
//deg2rad()函数将角度转换为弧度
$radLat1 = deg2rad($lat1);
$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 * 1000;
return $s;
}


        两种方法计算出来会有误差。