0

I'm trying to use the Google Maps API to return the journey time and length from one point to another. Here is my code.

var routeInfoObject;

function findRoutes(given_origin, given_destination){
  var directionsService = new google.maps.DirectionsService();

  var directionsRequest = {
    origin: given_origin,
    destination: given_destination,
    travelMode: google.maps.DirectionsTravelMode.WALKING,
    unitSystem: google.maps.UnitSystem.METRIC,
    provideRouteAlternatives: true
  };

  var times = new Array();
  var lengths = new Array();
  var positions = new Array();
  directionsService.route(directionsRequest, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
         for (i = 0; i < response.routes.length && i < 4 ; i++) 
         {
             times[i] = response.routes[i].legs[0].duration.text;
             lengths[i] = response.routes[i].legs[0].distance.text;
         }

         routeInfoObject = times;
      } else { 
         console.log("There was an error with the request") 
      }
  });

  console.log(routeInfoObject);
}

The log at the bottom always returns undefined, even though routeInfoObject is a global variable and should be set to the value of times. Logging the value of times inside the callback function if I run findRoutes("longsight","rusholme") returns [18,18,18].

Mark Brackett
  • 84,552
  • 17
  • 108
  • 152

1 Answers1

0

The callback function (function(response, status)) doesn't execute until after your console.log statement, so it's not assigned yet.

Mark Brackett
  • 84,552
  • 17
  • 108
  • 152
  • I'm confused, how can I fix this? Essentially I need to return a value from the callback to then be returned again from the findRoutes function. – RCarruthers Oct 25 '15 at 02:36
  • @user2952231 - you generally can't make an async api behave synchronously; you need to either pass a callback into findRoutes of what you want to do afterwards, or do a setTimeout/interval wait and check when routeInfoObject is no longer undefined. – Mark Brackett Oct 25 '15 at 03:21