2012-10-10 85 views
0

我有這個函數的一個問題:地理編碼器地理編碼 - 谷歌地圖的JavaScript API

function geo(address) { 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      return results[0].geometry.location; 
     } 
    }); 
} 

它返回我「未定義」。任何幫助將被認可。非常感謝!

回答

0

其實您的地理編碼是正確的。問題是「geocoder.geocode」是異步的,geo函數在獲取地理編碼結果之前完成執行。作爲一個概念證明,試試這個:

function geo(address) { 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 

      alert(results[0].geometry.location); //should have valid info 
      return results[0].geometry.location;      
     } 
    }); 

    alert("I bet you were not expecting this alert to go first");     
} 

所以,你有兩個選擇。要麼處理地理功能內的地理編碼位置,要麼使用處理位置的函數提供回調。

我已經用這個例子更新了你的小提琴。檢查它here

0

好的,謝謝。

我找到了其他解決方案 - 最好是將結果[0] .geometry.location中的值保存到cookie並在我需要的地方使用。不管怎麼說,還是要謝謝你!