回调函数返回未定义的值

时间:2015-10-25 02:07:30

标签: javascript callback undefined

我尝试使用Google Maps API将旅程时间和长度从一个点返回到另一个点。这是我的代码。

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);
}

底部的日志始终返回undefined,即使routeInfoObject是全局变量,也应设置为times的值。如果我运行findRoutes(&#34; longsight&#34;,&#34; rusholme&#34;),则返回回调函数内的时间值,返回[18,18,18]。

1 个答案:

答案 0 :(得分:0)

回调函数(function(response, status))在 console.log语句之后才会执行,因此尚未分配