我正在开发一张使用Google地图上各点之间距离的地图。
现在我遇到了一个问题,因为我对javascript的了解是初学者。我无法计算所有距离并将其放入数组中。 (需要检查所有距离并选择最接近的距离。)
到目前为止,这是我的代码:(第一个lat1,lng1是我的地理位置)(实时:http://www.cosound.nl/index-v01.html)
var locations = [
['ArtEZ Institute of the Arts', 51.983776, 5.893732, 5],
['Renssenstraat 9-12', 51.984874, 5.897199, 4],
['Utrechtsestraat 53', 51.983703, 5.897809, 3],
['Oude Kraan', 51.982593, 5.898420, 2],
['Montevia Studenthousing', 51.981833, 5.901081, 1 ]
];
// The above ones is my array of locations
var currentDist;
// This is the code I'm using to try and get back the distances.
// Assuming that I need to put some counter in the function....
function distance(lat1,lng1,lat2,lng2) {
var R = 6371; // km (change this constant to get miles)
var dLat = (lat2-lat1) * Math.PI / 180;
var dLon = (lng2-lng1) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
if (d>1) return d;
else if (d<=1) return Math.round(d*1000);
return d;
}
也许我可以使用for循环?
for (count = 0; count < locations.length; count++) {
}
自己试了一下:
for (count = 0; count < locations.length; count++) {
currentDist = distance(lat1,lng1,locations[count][1],locations[count][2]);
}
想将它们存储在数组中,或者至少能够在其他地方使用它们。
答案 0 :(得分:0)
您可以使用for循环并按下数组中的距离:
for (var i = 0; i < locations.length; i++) {
locations[i].push(distance(lat1, lng1, locations[i][1], locations[i][2]));
}