how to returning distance with function in google maps

旧城冷巷雨未停 提交于 2019-12-25 16:56:19

问题


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


来源:https://stackoverflow.com/questions/30629090/how-to-returning-distance-with-function-in-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!