Reputation: 43
I'm having difficulties to write a callback function to get a values from an asynchronous request made by google direction api, what I need here is to write a callback function that will get me the time when asynchronous request has completed. I wanted to do it by myself but i just don't understand why is it not working, following some examples that I've seen on this site this should be working.
here is my callback function
function getTime(myVar){alert(myVar);}
the function where the callback function is being called
function travellingTime(Origin, Destination, callback) {
var myVar;
var directionsService = new google.maps.DirectionsService();
var request = {
origin: Origin,
destination: Destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the distance:
//alert(response.routes[0].legs[0].distance.value + " meters");
// Display the duration:
//Time = (response.routes[0].legs[0].duration.value / 60);
myVar = (response.routes[0].legs[0].duration.value / 60);
callback(myVar);
}
});
}
triggering action on button
<button onclick="travellingTime('portlouis','vacoas',getTime())">TSP</button>
I'm still getting myVar
as undefined
when alert
Upvotes: 1
Views: 231
Reputation: 321
You are calling getTime and passing the result, just pass it without calling it.Like so(remove the pair of parenthesis).
<button onclick="travellingTime('port louis','vacoas',getTime)">TSP</button>
Upvotes: 1