PHP calculates the distance between two coordinates (longitude, latitude)

<?php

class Distance
{
    const  EARTH_RADIUS_AVG = (6378137 + 6356752.3142) / 2;//地球半径 平均值,单位米

    /**
     * 参数:纬度1,经度1、纬度2.经度2、
     * 使用Haversine公式,计算2个经纬度之间的距离。
     *
     * @param $lat1 纬度1
     * @param $lon1 经度1
     * @param $lat2 纬度2
     * @param $lon2 经度2
     * @return float|int 返回距离,单位:米
     */
    public static function GetDistance( $lat1,  $lon1,  $lat2,  $lon2)
    {
        //经纬度转换成弧度
        $lat1 = self::GetRadians($lat1);
        $lon1 = self::GetRadians($lon1);
        $lat2 = self::GetRadians($lat2);
        $lon2 = self::GetRadians($lon2);
        //差值
        $vLon = Abs($lon1 - $lon2);
        $vLat = Abs($lat1 - $lat2);
        $h = self::HaverSin($vLat) + Cos($lat1) * Cos($lat2) * self::HaverSin($vLon);
        $distance = 2 * self::EARTH_RADIUS_AVG * Asin(Sqrt($h));
        return $distance;
    }

    /**
     * 将角度换算为弧度
     *
     * @param $deg 角度
     * @return float 弧度
     */
    public static function  GetRadians( $deg)
    {
        return PI() * $deg / 180.0;
    }


    /**
     * 半正矢公式(Haversine公式)
     *
     * @param $theta
     * @return float|int
     */
    public static function HaverSin($theta)
    {
        $v = Sin($theta / 2);
        return $v * $v;
    }

}

$lat1 =39.929377;//纬度1
$lon1=116.408149;//经度1
$lat2=39.920054;//纬度2
$lon2=116.408545;//经度2
echo (new Distance())::GetDistance($lat1,$lon1,$lat2,$lon2); //输出:1036.6413225215(米);如果换算成千米,保留小数点后三位,结果为1.037(千米)

According to the result obtained by the online distance calculation tool is consistent with the above code execution results, the calculation result of the online distance calculation tool is shown in the figure below:

Online azimuth calculation website: azimuth online calculation--azimuth-distance online calculator

Guess you like

Origin blog.csdn.net/beenles/article/details/121477119