I count the shortest path to the destination point from many different origin points with google maps api. I decided to do it this way : (count for each pair of points than save results to array and than check at the end which is best). But i have problem with callback - because as comments says array is always zero - because this code is performed before all requests to count the route length.
function foo(){
var directionsService = new google.maps.DirectionsService();
var destination = new google.maps.LatLng(x,y);
var arrayOfRes= [];
for(var index in originPoints){
var request = {
origin:originPoints[index].marker.position,
destination:destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var res = {};
res.length = result.routes[0].legs[0].distance.value;
res.index = index;
res.result = result;
arrayOfRes.push(res);
}
});
}
//here arrayOfRes.length is always 0
if(arrayOfRes.length>1)
{
var bestResult = arrayOfRes[0];
for(var i = 1; i < arrayOfRes.length; i++)
{
if(bestResult.length > arrayOfRes[i])
bestResult = arrayOfRes[i];
}
console.log("Best is" + bestResult.length);
}
else if(arrayOfRes.length ==1)
{
var bestResult = arrayOfRes[0];
}
}
How to write function with callback so that it wait until all requessts are ended?