2009-11-29 32 views
4

我只是试图使用Google Maps API获取地图上2点的距离。使用GDirections。问题是函数完成后,距离总是空。我知道这是因为直到函数完成后才会调用“加载”事件。事件监听器不返回值,所以我很难过!来自Google Maps API中GEvent.addListener的返回值?

有没有人知道如何让这个函数返回距离?也许有更好的方法来获得谷歌地图API中2点之间的距离?

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 
} 

回答

2

GDirections加载是异步的。您将无法使用加载请求的结果,直到触发事件为止。这意味着你的getDistance函数刚刚设置了GDirections加载的请求,它将不能同步(立即)获得请求的结果。对象必须离开并向Google发出HTTP请求,以便它可以计算出两点之间的距离。

你需要做的就是把你的代码,使用距离为你传递给负载请求回调功能是什么:

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

下面是使用GDirections对象负载的例子(获得驾驶时间,而不是距离,但原理是一样的):

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

你可以找到源的H ere:

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