【问题标题】:Calculate km difference from two coordinates从两个坐标计算公里差
【发布时间】:2013-05-25 13:22:09
【问题描述】:

我要计算之间的距离

(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!
...

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

【问题讨论】:

  • 你能提供最小的例子吗?太多分散注意力的代码

标签: php coordinates distance


【解决方案1】:

根据这个答案:

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

  1. 您不能将度数转换为弧度。
  2. 你的公式不正确:

他们说:

 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】:

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

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

    查看this 函数。它看起来有点不同。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2017-05-30
      相关资源
      最近更新 更多