MBraiN
MBraiN

Reputation: 55

JQuery and Google Maps API

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?

Upvotes: 0

Views: 683

Answers (1)

Paul Sullivan
Paul Sullivan

Reputation: 2875

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

    }  

Upvotes: 1

Related Questions