我要计算
之间的距离(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!
...
问题出在哪里?有人可以帮我解决吗? :)
答案 0 :(得分:2)
答案 1 :(得分:2)
根据这个答案:
Calculate distance between two latitude-longitude points? (Haversine formula)
他们说:
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)
你指的是Haversine公式:
http://en.wikipedia.org/wiki/Haversine_formula
这些页面中有很多示例和代码片段:
我在代码中使用了这个代码段,效果非常好:
http://www.codecodex.com/wiki/Calculate_distance_between_two_points_on_a_globe#PHP