0

I have the following code; http://pastebin.com/Wf598D2E

But I can't get distance value to #result at first click. I have to click twice to see distance in #result. What's the problem with this code?

1 Answer 1

1

The reason is that the call to the google api is asynchronous and your code executes before the call returns populating the 'dist' value i.e.

calcRoute takes 500ms to return by which time your doc.ready method after that call has already executed.

The reason you see the value the second time is that the value you see is the result of the first calcRoute call

TO FIX:

simple one line amendment

    $(document).ready(function(){
            $("#send").click(function(event){
                    calcRoute();
            });

    });

    function calcRoute() {
      var start = document.getElementById("from").value;
      var end = document.getElementById("to").value;
      var ret = 0;
      var request = {
            origin:start,
            destination:end,
            travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(result, status) {
            //this is the onComplete method so do your UI amendments from in here
            if (status == google.maps.DirectionsStatus.OK) {
              directionsDisplay.setDirections(result);
              dist = result.routes[0].legs[0].distance.value;
              $("#result").html(dist);
            }else{
                    alert("Error");
            }
      });  

    }  
Sign up to request clarification or add additional context in comments.

5 Comments

check documentation for directionsService.route i bet it has a method signature of directionsService.route(request, function, function)... the second function is for onComplete. Check documentation you are looking for a way of executing a function on asynchronous call completion
ignore above cmment I am amending the answer to include fix
Thank you. But, is there a way like i did? Because the code is sample. I use "dist" variable in somewhere else.
The dist variable is still available BUT if you use the variable too soon your dist variable value MAY be old data (or null). Basically the easiest way to update all your other logic that MUST see thatest data is to call the methods from within the onComplete method. There are ways of calling methods outside the onComplete method but then you will have to do some queing code - non-trivial

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.