how to returning distance with function in google

2019-09-05 15:18发布

问题:

i've script from this link here and i want to make the function returning distance, this's my actually script :

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

there are two parameters that I put in function, and i want the function returning the distance but

return dist;

in the script not returning the value from

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

i'm using angularjs and the resto in my View not showing the distance, anyone help me please, there's something wrong with the script or anything else ?

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