Returns a value from GEvent.addListener to the Google Maps API?

I'm just trying to get the distance from 2 points on the map using the Google Maps API. Using GDirections. The problem is that after the function finishes, the distance is always zero. I know this happens because the load event is not called until the function completes. An event listener does not return a value, so I'm at a standstill!

Does anyone know how I can make this function return a distance? Perhaps there is a better way to get the distance between two points in the 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 } 
+4
source share
1 answer

Downloading GDirections is asynchronous. You cannot use the results of the download request until the download event is fired. This means that the getDistance function simply sets the GDirections download request, it will not be able to receive the request results synchronously (immediately). The GDIrections object must go away and make an HTTP request to Google so that it can determine the distance between the two points.

What you need to do is put your code that uses the distance to the callback function that you passed in the download 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 duration of the movement, not the distance, but the principle is the same):

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

Here you can find the source:

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

+2
source

All Articles