0

我从这里的链接中编写了脚本我想让函数返回距离,这是我的实际脚本:

var calcRoute = function(origin,destination) {
    var dist;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
  var request = {
    origin:origin,
    destination:destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      dist = response.routes[0].legs[0].distance.value / 1000;
    }
  });
    return dist;
};
$scope.resto = calcRoute("-7.048357, 110.418877","-7.048443, 110.441022");

我在函数中输入了两个参数,我希望函数返回距离,但是

return dist;

在脚本中没有返回值

dist = response.routes[0].legs[0].distance.value / 1000

我正在使用angularjs,而我的视图中的resto没有显示距离,请任何人帮助我,脚本有问题或其他什么问题?

4

1 回答 1

1

Until the directionsService.route function is executed the function calcRoute has already executed and returned dist which will be undefined.

You will get the value inside the callback function of directionsService.route

You can add another parameter (a callback function) to calcRoute function. Now once directionsService.route gets the response you can pass the value to this new callback function.

Try this.

var calcRoute = function(origin,destination,cb) {
    var dist;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
  var request = {
    origin:origin,
    destination:destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      cb(null, response.routes[0].legs[0].distance.value / 1000);
    }
    else {
      cb('pass error information');
    }
  });
};
calcRoute("-7.048357, 110.418877","-7.048443, 110.441022", function (err, dist) {
    if (!err) {        
      $scope.resto = dist;
    }
});
于 2015-06-03T19:38:30.943 回答