如何计算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 formula开头的行。如果我错了,请指出我的错误,也许是一个帮助解决方案?
答案 0 :(得分:2)
google maps V3中的computeLength()函数可以为您提供所需内容,请参阅http://code.google.com/intl/el/apis/maps/documentation/javascript/geometry.html#Distance
答案 1 :(得分:0)
您正在使用的功能是两个坐标之间的距离。您需要计算距离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;
}