问题描述
|
我不太使用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);
所以很显然,当我调用此函数时,由于循环结束且google处理程序尚未接收到数据,因此destn的值显示为undefined。如果我再调用该函数1次,则会得到从上一个回调(之前给出未定义)接收到的destn值。
有人告诉我如何解决这个问题。
解决方法
您需要等待,直到所有三个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,locationCount) {
// increment callback count
callbackCount++;
if (callbackCount == locationCount) { // all responses have returned
// do your distance checking
....
}
}
,退出for循环时,ѭ3中没有值,因为从it 4中收到结果后,它是异步设置的。相反,您需要跟踪已返回的请求数量,并在收到所有响应后从响应回调中调用函数:
... // your code
var responseCount = 0;
for (var i = 0; i < locations.length; i++) {
... // your code
directionsService.route(request,status) {
... // your code
if (++responseCount == locations.length) {
calcShortestRoute(origin,destn);
}
});
}
编辑:我重新阅读了您的问题,并认为我更了解您的代码在做什么。这个答案应该更准确(引导起来也更简洁!)。