计算谷歌地图的多个位置的距离

时间:2012-01-26 19:05:31

标签: javascript google-maps google-maps-api-3

假设我有3个位置,即Kallang(A),Paya Lebar(B)和Bedok(C)。我尝试做A-> B + B-> C但距离总是返回A-> C。为什么会这样?

kallang to paya lebar(A-B) - > 2.5914199062350742 km

paya lebar to bedok(B-C) - > 4.4403012109180775公里

总计(A-B-C) - > 7.03公里

kallang to bedok(A-C) - > 6.88公里

以下是我的代码:

var R = 6371; 
    var dLat = toRad(location3.lat()-location2.lat()) + toRad(location2.lat()-location1.lat());
    var dLon = toRad(location3.lng()-location2.lng()) + toRad(location2.lng()-location1.lng());

    var dLat1 = toRad(location1.lat());
    var dLat2 = toRad(location2.lat());

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(dLat1) * Math.cos(dLat1) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;

    document.getElementById("distance_direct").innerHTML = "<br/><br/><br/>The distance between the five points (in a straight line) is: "+d +" km.";
}

function toRad(deg) 
{
    return deg * Math.PI/180;
}

我的加法和减法计算语句有问题吗???感谢

2 个答案:

答案 0 :(得分:3)

您可以使用geometry library

中内置的computeDistanceBetween方法

答案 1 :(得分:2)

是的,问题在于添加和减少相同的东西。由于toRad()只是一个乘法,因此它与+和 - 相关联,因此

var dLat = toRad(location3.lat()-location2.lat())
         + toRad(location2.lat()-location1.lat());

完全相同
var dLat = toRad(location3.lat()-location1.lat());

所以你最终计算出第一个和最后一个点之间的直线距离。

如果您使用的是Google Maps JavaScript API V3,则可以加载Geometry Library并执行此操作:

var indirect_distance = 
    google.maps.geometry.spherical.computeDistanceBetween(location1, location2)
  + google.maps.geometry.spherical.computeDistanceBetween(location2, location3);