I am working on project dealing with the Google Maps API and I am trying to get the duration between multiple trips and tell what trips are shorter based on time. I was getting weird values in my object so I put some print statements outside of the directionsService and inside of it to. Code:
//loop through all the trips being made
for (i = 0; i < destinationsArray.length; i++) {
//request holds the information for the directions request
var request = {
origin: destinationsArray[i].from,
destination: destinationsArray[i].to,
travelMode: google.maps.TravelMode.TRANSIT,
transitOptions: {
modes: ['BUS'],
routingPreference: 'LESS_WALKING',
arrivalTime: today.now,
}
}
let directionsService = new google.maps.DirectionsService();
let companyID = destinationsArray[i].id;
console.log(i + " outside")
directionsService.route(request, function(reponse, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(i + " inside")
//create a new direction render for clickable options
let dirRender = new google.maps.DirectionsRenderer({map: map});
//push this new direction render onto the array
directionsRenderers.push(dirRender)
//create object to hold data about this current trip: trip length and company name
let tripInformation = {duration: reponse.routes[0].legs[0].duration.value, id: companyID}
//put this var into array
//console.log(tripInformation)
durationArray.push(tripInformation)
//this line puts the trip onto the map to see
directionsRenderer.setDirections(reponse);
} else {
alert("Could not display directions due to: " + status);
}
}
);
}
the print statements are coming out like so: 0 outside 1 outside 0 inside 0 inside
the destinationsArray is here if needed:
var destinationsArray = [
{id: "Trip 1", to: "John Ball Park Zoo", from: "Rosa Parks Circle"},
{id: "Trip 2", to: "10897 48th Ave NW", from: "1 Campus Drive Allendale"}
];