我不常使用 javascript,所以我对回调和响应不是很熟悉。我正在使用谷歌地图绘制点 A 和点 X、Y、Z 之间的距离。问题是,我想使用 javascript 来确定 X、Y、Z 中的哪一个点最接近 A,然后它们绘制出它们之间的方向。
我的代码运行正常。我可以算出所有 3 个目的地的最短距离,但我仍然坚持这种愚蠢的外观。
您知道,Google 使用异步回调向浏览器提供数据,如果我运行 for 循环来逐一检查所有 3 个目的地,我会得到不正确的结果。
代码如下:
var maxDistance = 99999999999;
var destn;
for (var i = 0; i < locations.length; i++) {
var thisDistance = 0;
var start = origin;
var end = locations[i];
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
thisDistance = response.routes[0].legs[0].distance.value;
if (thisDistance < maxDistance) {
destn = response.routes[0].legs[0].end_address;
maxDistance = thisDistance;
}
} else {
document.getElementById("addressNotFound").style.display = 'block';
}
});
}
calcShortestRoute(origin, destn);
很明显,当我调用此函数时,destn 的值出现为未定义,因为循环结束并且 google 处理程序尚未收到数据。如果我再调用该函数 1 次,我会得到从上一个回调中收到的 destn 值(之前给出了 undefined)。
有人请告诉我如何解决这个问题。
最佳答案
您需要等到所有三个 Google 响应都已返回。一个简单的解决方案是:将你的距离计算函数调用移到最后的匿名函数中,然后仅在所有响应都返回时才计算距离:
// global count variable
var callbackCount = 0;
for (var i = 0; i<locations.length; i++) {
var thisDistance=0;
var start = origin;
var end = locations[i];
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
thisDistance = response.routes[0].legs[0].distance.value;
if (thisDistance < maxDistance) {
destn = response.routes[0].legs[0].end_address;
maxDistance = thisDistance;
}
}
else {
document.getElementById("addressNotFound").style.display = 'block';
}
// move this to here, and pass in number of locations
calcShortestRoute(origin, destn, locations.length);
});
}
然后 calcShortestRoute 看起来像:
function calcShortestRoute(origin, destn, locationCount) {
// increment callback count
callbackCount++;
if (callbackCount == locationCount) { // all responses have returned
// do your distance checking
....
}
}
关于javascript - 在通过 javascript(也是谷歌地图)传递值之前等待循环完成。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653627/