如何计算两个纬度和经度之间的距离

时间:2016-03-11 20:20:51

标签: javascript geolocation geocoding 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>

当我运行此代码时,我会得到完全不同的数字。

1 个答案:

答案 0 :(得分:1)

我认为你应该期待更多像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>
相关问题