要透過兩組經緯度座標找到地表兩點的距離,必須要用地球表面距離公式計算距離。以下是PHP計算範例:
function getDistance($lat1,$lng1,$lat2,$lng2)
{
$earthRadius = 6367000;//approximate radius of earth in meters
/*
Convert these degrees to radians
to work with the formula
*/
$lat1 = deg2rad($lat1);
$lng1 = deg2rad($lng1);
$lat2 = deg2rad($lat2);
$lng2 = deg2rad($lng2);
/*
Using the
Haversine formula
http://en.wikipedia.org/wiki/Haversine_formula
calculate the distance
*/
$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);
}
沒有留言:
張貼留言