我有一个javascript函数,应该返回字符串的地理编码:
function codeAddress(address) {
var result = (new google.maps.Geocoder()).geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return String(results[0].geometry.location.Ya)+','+String(results[0].geometry.location.Za)
} else {
return status;
}
});
console.log(result);
return result
}
然而它返回“undefined”。我理解这里的错误,即,因为javascript是异步的,它甚至在codeAddress
完全执行之前从函数function(results, status)
返回。但我需要知道这里的解决方案和最佳实践。
答案 0 :(得分:11)
由于它是异步的,你应该传递一个处理函数的回调:
function codeAddress(address, callback) {
(new google.maps.Geocoder()).geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(String(results[0].geometry.location.Ya) + ','
+ String(results[0].geometry.location.Za))
} else {
callback(status);
}
});
}
codeAddress("test", function(result) {
// do stuff with result
});
如果你正在使用jQuery,你也可以使用deferred:
function codeAddress(address, callback) {
var dfd = new jQuery.Deferred();
(new google.maps.Geocoder()).geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// trigger success
dfd.resolve(String(results[0].geometry.location.Ya) + ','
+ String(results[0].geometry.location.Za));
} else {
// trigger failure
dfd.reject(status);
}
});
return dfd;
}
codeAddress("some address").then(
// success
function(result) {
// do stuff with result
},
// failure
function(statusCode) {
// handle failure
}
);