[英]Wait for Loop to finish before passing the value in javascript (also google maps).
我不使用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。 如果我再多次調用該函數,我會得到從前一個回調函數收到的destn值(之前給出了undefined)。
有人請告訴我如何解決這個問題。
退出for循環時, destn
沒有值,因為在從directionsService.route()
收到結果后,它是異步設置的。 相反,您需要跟蹤已返回的請求數,並在收到所有響應后從響應回調中調用您的函數:
... // your code
var responseCount = 0;
for (var i = 0; i < locations.length; i++) {
... // your code
directionsService.route(request, function(response, status) {
... // your code
if (++responseCount == locations.length) {
calcShortestRoute(origin, 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, destn, locationCount) {
// increment callback count
callbackCount++;
if (callbackCount == locationCount) { // all responses have returned
// do your distance checking
....
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.