[英]how to calculate distance between two latitude and longitude using angulajs?
[英]How to calculate the distance between two latitude and longitude
我正在嘗試使用他們的緯度和經度來計算溫哥華和多倫多之間的距離。 我正在使用Haversine公式。 我預計將達到4390公里。 有人可以告訴我我正在犯什么錯誤。 這是我的代碼:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="getDistance()">
<script>
// Convert Degress to Radians
function Deg2Rad( deg ) {
return deg * Math.PI / 180;
}
function getDistance()
{
//Toronto Latitude 43.74 and longitude -79.37
//Vancouver Latitude 49.25 and longitude -123.12
lat1 = Deg2Rad(43.74);
lat2 = Deg2Rad(49.25);
lon1 = Deg2Rad(-79.37);
lon2 = Deg2Rad(-123.12);
latDiff = lat2-lat1;
lonDiff = lon2-lon1;
var R = 6371000; // metres
var φ1 = lat1;
var φ2 = lat2;
var Δφ = Deg2Rad(latDiff);
var Δλ = Deg2Rad(lonDiff);
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
alert('d: ' + d);
var dist = Math.acos( Math.sin(φ1)*Math.sin(φ2) + Math.cos(φ1)*Math.cos(φ2) * Math.cos(Δλ) ) * R;
alert('dist: ' + dist);
}
</script>
</body>
</html>
當我運行此代碼時,我得到的數字完全不同。
我認為您應該期望超過3358公里。 http://www.distancefromto.net/distance-from/Toronto/to/Vancouver
這是正確結果的小提琴: https : //jsfiddle.net/Lk1du2L1/
在這種情況下,如果您要從次要結果中刪除deg2rad,那將是正確的-您經常這樣做:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="getDistance()">
<script>
// Convert Degress to Radians
function Deg2Rad( deg ) {
return deg * Math.PI / 180;
}
function getDistance()
{
//Toronto Latitude 43.74 and longitude -79.37
//Vancouver Latitude 49.25 and longitude -123.12
lat1 = Deg2Rad(43.74);
lat2 = Deg2Rad(49.25);
lon1 = Deg2Rad(-79.37);
lon2 = Deg2Rad(-123.12);
latDiff = lat2-lat1;
lonDiff = lon2-lon1;
var R = 6371000; // metres
var φ1 = lat1;
var φ2 = lat2;
var Δφ = latDiff;
var Δλ = lonDiff;
var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
alert('d: ' + d);
var dist = Math.acos( Math.sin(φ1)*Math.sin(φ2) + Math.cos(φ1)*Math.cos(φ2) * Math.cos(Δλ) ) * R;
alert('dist: ' + dist);
}
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.