3 回答

TA贡献1884条经验 获得超4个赞
您无法从函数返回值,该函数返回时该值尚不存在。
该geocode方法进行异步调用并使用回调来处理结果,因此您必须在codeLatLng函数中执行相同的操作:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng(function(addr){
alert(addr);
});
}
function codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}

TA贡献1946条经验 获得超3个赞
您正在发起一个异步请求,您的codeLatLng()函数已经完成并且在地理编码器完成之前返回了很长时间。
如果您需要继续使用地址解析器数据,则必须将功能链接在一起:
function initialize() {
geocoder = new google.maps.Geocoder();
codeLatLng();
}
function codeLatLng() {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
initContinued(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
function initContinued(addr) {
alert(addr);
}
添加回答
举报