Here is my sample code
var selected_path = [];
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
}
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path = selected_path.concat(results.routes[0].overview_path);
}
})
}
console.log(selected_path); // slected_path in console is []
poly.setPath(selected_path);
poly.setMap(map);
In this situation selected_path in console is []. When I add alert(i) line before console.log(selected_path). Here is code after addition:
var selected_path = [];
for (var i = 0; i <path.length-1; i++) {
var request = {
origin: path[i],
destination: path[i+1],
travelMode: google.maps.DirectionsTravelMode.WALKING
}
directionsService.route(request, function(results, status) {
if (status == google.maps.DirectionsStatus.OK) {
selected_path = selected_path.concat(results.routes[0].overview_path);
}
})
}
alert(i) ////// ADDED ONE LINE
console.log(selected_path); /// selected_path in console has proper value
poly.setPath(selected_path);
poly.setMap(map);
Variable i is showing like an alert on screen and variable selected_path has proper value. Could somebody explain it to me, because I dont’t get it. To clarify it works in firefox, probably not in chrome.
I think this is due to the asynchronous behaviour of the
directionsService.routemethod. It calls the callback function after the ajax call has finished.So when you show the alert, execution of the code afterwards (console.log) is posponed until you click the OK button. That is enough time for the ajax call to finish and populate the
selected_pathvariable. In the version without the alert there is no such delay so the ajax call has not finished yet and most likely could not have populatedselected_pathbefore the console.log runs.To fix this you can do two things:
selected_pathhas been filled in the callback function as well.So the first solutions would be to do this:
The second would be this:
If possible I’d use the first one.