2009-11-29 14 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