javascript - how to returning distance with function in google maps -


i've script link here , want make function returning distance, this's 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 2 parameters put in function, , want function returning distance

return dist;

in script not returning value

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

i'm using angularjs , resto in view not showing distance, me please, there's wrong script or else ?

until directionsservice.route function executed function calcroute has executed , returned dist undefined.

you value inside callback function of directionsservice.route

you can add parameter (a callback function) calcroute function. once directionsservice.route gets response can pass value 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;     } }); 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Website Login Issue developed in magento -

Can the constants be defined inside a model file of a framework in PHP? -