views:

700

answers:

1

I am simply trying to get the distance from 2 points on a map using the Google Maps API. Using GDirections. The problem is that after the function finishes, distance is always null. I know this is because the "load" event isn't being called until after the function finishes. The Event Listener doesn't return values either so I am stumped!

Does anybody know how I can make this function return the distance? Perhaps there is a better way to get the distance between 2 points in Google Maps API?

function getDistance(fromAddr, toAddr) {    
var distance;
var directions;

directions = new GDirections(null, null);
directions.load("from: " + fromAddr + " to: " + toAddr);

GEvent.addListener(directions, "load", function() {
 distance = directions.getDistance().html;
 distance = distance.replace(/&.*/, '');
});

return distance; //outputs null
}
+1  A: 

GDirections load is asynchronous. You won't be able t use the results of your load request until the load event is fired. This means that your getDistance function just sets up the GDirections load request, it won't be able to get the results of the request synchronously (immediately). The GDIrections object has to go away and make a HTTP request to Google so that it can work out the distance between the two points.

What you need to do is put your code that uses the distance into the callback function that you passed to the load request:

GEvent.addListener(directions, "load", function() {
            // this is a callback function that is called after 
            // the getDistance function finishes.
            var distance = directions.getDistance().html;

            // Have a distance now, need to do something with it.
            doSomethingWithTheDistanceWeGotBack (distance);
    });

Here is an example of using GDirections load (getting the driving duration, not the distance, but the principle is the same):

http://www.cannonade.net/geo.php?test=geo6

You can find the source here:

http://www.cannonade.net/geo6.js

Cannonade