[英]Google reverse geocode return variable
我有以下代碼:
var reverseGeo = function (latitude, longitude){
var address1;
var geocoder = new google.maps.Geocoder();
var location = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({'latLng': location}, function(results, status){
if(status === google.maps.GeocoderStatus.OK){
if(results[0]){
address1 = results[0].formatted_address;
//console.log(address1);
}
else{
console.log(status);
}
}
});
console.log(address1);
};
第一個console.log();
被注釋掉是正確的。 它包含格式化的地址。 底部的第二個console.log()
是undefined
。 我在這里想念什么? 此外,我需要將此address1
變量返回到直接調用此腳本的父javascript文件。 無論我如何嘗試,除了geocoder.geocode();
本地代碼,我到處都undefined
geocoder.geocode();
您在理解javascript和回調函數的異步功能時遇到問題
geocoder.geocode函數接受回調函數作為其第二個參數。 每當檢索地址時,將異步調用此函數。
最后的console.log將無法工作,因為在調用geocoder.geocode()函數之后,該程序將不會等待回調函數被調用,而是立即執行下一條指令。 在這種情況下,address1變量將尚未填充。
您真正要尋找的是一個接受您所在位置的函數和一個回調函數。 像這樣:
function getAddress(location, callback){
geocoder.geocode({'latLng': location}, function(results, status){
if(status === google.maps.GeocoderStatus.OK){
if(results[0]){
var address1 = results[0].formatted_address;
callback(address1);
}
}
});
}
現在,從您要使用該地址的另一個文件中,您可以像下面這樣調用此函數:
var location = new google.maps.LatLng(latitude, longitude);
getAddress(location, function(address)
{
console.log(address);
});
在這里,檢索地址后,將調用您定義的接受地址的函數,並且地址變量將對您可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.