计算两个坐标的km差

时间:2013-05-25 13:22:09

标签: php coordinates distance

我要计算

之间的距离
(40.851774999999996,14.268123999999998)

并且每个坐标都进入sql查询的结果:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $key => $value) {
    echo "distance = ". calculateDistance("40.851774999999996","14.268123999999998",$value['lat'],$value['lng'])."<br>"; 
}

calculateDistance

的位置
function calculateDistance($targetLat,$targetLng,$currentLat,$currentLng){
    $r    = 6371; // km
    $dLat = $targetLat-$currentLat;
    $dLng = $targetLng-$currentLng; 
    $a    = sin($dLat/2)*sin($dLat/2) + sin($dLng/2)*sin($dLng/2); 
    $c    = 2*atan2(sqrt($a), sqrt(1-$a));
    return $r*$c;
}
它给了我奇怪的结果,如:

distance = NAN //-> NAN???
distance = 3392.8405117312 // TOO MUCH!
distance = 3392.8405117312 // TOO MUCH!
...

问题出在哪里?有人可以帮我解决吗? :)

3 个答案:

答案 0 :(得分:2)

sin函数中使用它之前,您需要将度数转换为弧度。

$radians = $degrees * (M_PI/180);

同样查看this功能。它看起来有点不同。

答案 1 :(得分:2)

根据这个答案:

Calculate distance between two latitude-longitude points? (Haversine formula)

  1. 您不会将度数转换为弧度。
  2. 您的公式不正确:
  3. 他们说:

     var a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
    

    您写道:

    $a = sin($dLat/2)*sin($dLat/2) + sin($dLng/2)*sin($dLng/2); 
    

    代码中缺少余弦。

答案 2 :(得分:0)