PHP代码:计算两坐标点之间的距离

地球上两个点之间,可近可远。
当比较近的时候,可以忽略球面因素,当做是一个平面,这样就有了两种计算方法。

//两点间距离比较近
function getDistance($lat1, $lng1, $lat2, $lng2) 
{ 
    $earthRadius = 6367000; //地球半径m

    $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); 
} 

//两点间距离比较远
function getLongDistance($lat1, $lng1, $lat2,$lng2,$radius = 6378.137)
{
    $rad = floatval(M_PI / 180.0);

    $lat1 = floatval($lat1) * $rad;
    $lng1 = floatval($lng1) * $rad;
    $lat2 = floatval($lat2) * $rad;
    $lng2 = floatval($lng2) * $rad;

    $theta = $lng2 - $lng1;

    $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));

    if ($dist < 0 ) {
        $dist += M_PI;
    }
    return $dist = $dist * $radius;
}

你可能感兴趣的:(代码片段)