2015-08-18 92 views
-2

我想通過谷歌api v3地理編碼功能返回地址的經度和緯度。地理編碼工作正常我只是不能將結果設置爲我的地理編碼obj從函數返回。我懷疑這是一個範圍問題谷歌地圖Api v3地理編碼地址,如何返回對象

function codeAddress(address) { 
    var geocoder = new google.maps.Geocoder(); 

    //this is the container var which I will reurn 
    var geocode={}; 

geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     geocode.success = true; 
     geocode.position= results[0].geometry.location; 
    //If I log geocode here I can see the position and success values in the object 
    } else { 
     geocode.success=false; 
     geocode.message="Geocode was not successful for the following reason: " + status; 

    } 
}); 

    //If I log geocode here it's empty 

    return geocode; 
} 

任何意見讚賞。

+0

地理編碼器是異步的。你不能從它的回調例程中「返回」任何東西,你需要在回調函數中有/可用的地方使用這些數據。 – geocodezip

回答

0

這絕對是一個範圍問題。傳遞給地理編碼請求的回調函數是異步執行的。

訪問地理編碼服務是異步的,因爲Google地圖 API需要調用外部服務器。因此, 需要傳遞迴調方法,以在完成 請求時執行。這個回調方法處理結果。

Source

這意味着你的codeAddress函數總是返回一個空的對象。

+0

歡呼,通過回調功能,一切都很好:-) –

相關問題