I have a Google Distance Matrix working, but need to account for more than 25 destinations, so I'm breaking my array into slices to send 25 destinations at a time. It works, sort of, but the thing I don't understand is the ORDER of how FOR, Functions, and Callbacks work. The callback logs all happen after the FOR loop completes, but they actually have the right data in them, I don't understand why.
This leaves me unable to check for the completion of the FOR loop, because the callbacks won't have happened, so I can't get to the array that is being built from the object that Google kicks back as a response.
Assume that xx starts at 0, and the destination[] is working list of lat/longs.
These are output in console (not variables):
calculate = 1
calculate = 2
calculate = 3
calculate = 4
after for = 4
callback = 4
callback = 4
callback = 4
callback = 4
This is the chunk of code in question:
var ii,jj,tempServArr,maxZips = 25;
for (ii=0,jj=destinations.length; ii<jj; ii+=maxZips) {
tempServArr = destinations.slice(ii,ii+maxZips);
xx++;
calculateDistances(zip_latlng, tempServArr);
}
console.log("after for = ",xx);
});
});
}
function calculateDistances(origin, destinations) {
console.log("calculate = ",xx);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
console.log("callback = ",xx);
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {