【问题标题】:How to calculate distance between five markers?如何计算五个标记之间的距离?
【发布时间】:2012-02-18 21:34:38
【问题描述】:

如何计算 Google 地图 V3 中五个标记之间的距离?我知道我必须使用我研究过的 Haversine 公式,甚至在这里找到了一个关于计算两个标记之间距离的帖子。如果我想在五个标记之间计算它怎么办?尝试了几个小时,但计算出的公里数非常错误。谢谢

以下代码如下:

// compute distance between the two points
    var R = 6371; // KM
    var dLat = toRad(location5.lat()-location4.lat()-location3.lat()-location2.lat()-location1.lat());
    var dLon = toRad(location5.lng()-location4.lng()-location3.lng()-location2.lng()-location1.lng()); 

    var dLat1 = toRad(location1.lat());
    var dLat2 = toRad(location2.lat());
    var dLat3 = toRad(location3.lat());
    var dLat4 = toRad(location4.lat());
    var dLat5 = toRad(location5.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;
}

我想我的错误之处在于以 var a 公式开头的行。如果我错了,请指出我的错误,也许有帮助的解决方案?

【问题讨论】:

  • “五个标记之间的距离”是什么意思?
  • 这不只是加法(标记 A 和 B 之间的距离 + B 和 C + 之间的距离等)吗?
  • @AakashM 谷歌地图中以直线连接的五个坐标点之间的距离。
  • @KevinDTimm 我确实尝试了你几个小时前所说的,但我无法让它正常工作。请问您可以编辑我的或发布解决方案吗?
  • 既然你说你知道如何计算两点之间的距离,那你肯定只是添加距离 A-B、B-C 等?

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


【解决方案1】:

谷歌地图 V3 中的 computeLength() 函数应该可以满足您的需求,请参阅 http://code.google.com/intl/el/apis/maps/documentation/javascript/geometry.html#Distance

【讨论】:

    【解决方案2】:

    您使用的函数是两个坐标之间的距离。您需要计算从 A->B 到 B->C 的距离,然后将这些距离加起来。

    var distAB = calcDist(location1,location2);
    var distBC = calcDist(location2,location3);
    var distCD = calcDist(location3,location4);
    var distDE = calcDist(location4,location5);
    
    var distTotal = distAB + distBC + distCD + distDE;
    
    function calcDist(locationA,locationB)
    {
        var R = 6371; // KM
        var dLat = toRad(locationB.lat()) - toRad(locationA.lat());
        var dLng = toRad(locationB.lng()) - toRad(locationA.lng());
        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)); 
        return R * c;
    }
    
    function toRad(deg) 
    {
        return deg * Math.PI/180;
    }
    

    【讨论】:

    • 在我传递这些位置对象的地方,Javascript 可能是错误的(我不经常使用 JS)。但是如果你想做计算,那就是如何去做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2010-09-26
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多