2016-04-17 48 views
0

我正在開發一個應用程序,我需要從地理編碼文本地址派生的console.log地理座標。我用javascript編寫了以下代碼:如何使用谷歌地理編碼將地址轉換爲座標後的console.log數據?

var geocoder = new google.maps.Geocoder(); 

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

     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } 

    console.log(address_to_coordinates('London')); 

由於某種原因,它在控制檯中輸出'undefined'。有沒有人看到它的原因?

回答

0

你需要使用回調

var geocoder = new google.maps.Geocoder(); 

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

     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } 

address_to_coordinates('London', function(location){ 
    console.log(location); 
}); 
+0

如果我嘗試只通過回調以獲取緯度(結果[0] .geometry.location.latitude);在你的代碼中。我仍然不確定,你知道這是爲什麼嗎? –

+0

由於回調函數中的參數已經是'results [0] .geometry.location' –

相關問題