0

I tried and search many questions but not able to solve this problem. I actually want to get calculated distance value from function of a function but on first execution it is returning undefined value, but when i execute second time it returns the proper value.

var directionsService = new google.maps.DirectionsService();
var Distance;

// Calculate Distance


function calcRoute() {
    var source = document.getElementById("txtSource").value;
    var destination = document.getElementById("txtDestination").value;
    var distanceInput = document.getElementById("distance");

    var request = {
        origin: source,
        destination: destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            Distance = response.routes[0].legs[0].distance.value / 1000;
        } else {
            alert("Unable to find the distance via road.");
        }
    });
    alert("if condition value is : " + Distance);

}
  • 1
    The problem is that `directionsService.route` is asynchronous. Your variable `Distance` doesn't get assigned anything until the request from `directionsService.route()` has some data. By this time you have already called your `alert()`. You need to deal with `Distance` inside the callback or pass it to another function from within the callback. See also: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Mark May 06 '18 at 21:52
  • 1
    Thanks @Mark_M, I passed the `Distance` to another function, its working. – Ranjit Singh Shekhawat May 06 '18 at 22:04

1 Answers1

0

As you can see, directionsService.route accepts the request and a function that will be executed asynchronously (it’s basically a promise that the function you pass as the second argument will be executed once the Google service completes your request).

Until that function is executed, the program continues its execution (so it goes to the alert line). At that point, you may or may have not the computed value of the Distance variable (depending on the execution of the previous function).

In order to be sure that you have the value from the directionsService.route callback, you can move the alert inside that function, or you may call another function (defined by you) passing the Distance as a parameter.