I have two Arrays (gOriginsArray, gDestinationsArray) which are Array of Arrays and I am storing 10 addresses in each array and I have close to 300 origins addresses and 300 destinations address stored in a sets of 10 entries. My gOriginsArray has 300 identical elements. I am running a loop and sending 10 addresses from both array to calculate the distance but my loop carries on before I get result from DistanceMatrixService and I get OVER_QUERY_LIMIT error as well.
I want to find the distance of all 300 addresses and then run LoadBookingsArray(Records) function.
for (var k = 0; k < gDestinationsArray.length; k++) {
var DistanceService = new google.maps.DistanceMatrixService();
DistanceService.getDistanceMatrix({
origins: gOriginsArray[k],
destinations: gDestinationsArray[k],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var results = response.rows[0].elements;
for (var l = 0; l < results.length; l++) {
gDistanceArray.push(results[l].distance.text);
}
} else if (status === google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
console.log('OVER_QUERY_LIMIT');
}, 10000);
} else {
console.log(status);
gDistanceArray.push('');
}
});
}
LoadBookingsArray(Records);
My Updated version with async/await
async function RunBookings() {
for (var k = 0; k < gDestinationsArray.length; k++) {
let promise = new Promise(function(resolve, reject) {
var DistanceService = new google.maps.DistanceMatrixService();
DistanceService.getDistanceMatrix({
origins: gOriginsArray[k],
destinations: gDestinationsArray[k],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(response);
var results = response.rows[0].elements;
for (var l = 0; l < results.length; l++) {
gDistanceArray.push(results[l].distance.text);
}
resolve('Good promise');
} else if (status === google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
console.log('OVER_QUERY_LIMIT');
console.log(response);
console.log(status);
reject(Error("Bad promise"));
} else {
console.log('BAD');
console.log(response);
console.log(status);
reject(new Error("Bad promise"));
}
});
});
let result = await promise;
}
}