0

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"}
];
  • this is normal behavior. with `directionsService.route` you are sending an async request. The request's can take different amount of time to finished. – Sysix Mar 03 '21 at 18:56
  • @Sysix I suspected that could be the possibility. How might I attach the companyID if the two are out of sync? –  Mar 03 '21 at 18:58
  • maybe splitting it into function would help, looks like a scope problem for me :) – Sysix Mar 03 '21 at 19:08

1 Answers1

1

Consider this code:

for(x = 0; x < 5; ++x) {
    setTimeout(() => console.log(x))   // Outputs 5, 5, 5, 5, 5
}

Versus this:

    for(let x = 0; x < 5; ++x) {
        setTimeout(() => console.log(x))   // Outputs 0, 1, 2, 3, 4
    }

Please see here for detailed explanation

peter
  • 583
  • 2
  • 11
  • another reason why I live modern IDE's :) They give automatic warning's when you didn't define a variable – Sysix Mar 03 '21 at 20:22