如何从 Google Maps JavaScript 地理编码器回调返回变量? [英] How do I return a variable from Google Maps JavaScript geocoder callback?
问题描述
我正在使用 google maps API,每当我将变量从 codeLatLng 函数返回到 initialize 函数时,它都声称未定义.如果我从 codeLatLng 打印变量,它会显示正常.
I am working with the google maps API and whenever I return the variable to the initialize function from the codeLatLng function it claims undefined. If I print the variable from the codeLatLng it shows up fine.
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
var addr = codeLatLng();
document.write(addr);
}
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]) {
return results[1].formatted_address;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
打印出未定义
如果我这样做:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
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]) {
document.write(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
打印出纽约,NY 10012,美国
prints out New York, NY 10012, USA
推荐答案
不能从函数返回值,函数返回时值还不存在.
You can't return the value from the function, the value doesn't exist yet when the function returns.
geocode
方法进行异步调用并使用回调来处理结果,因此您必须在 codeLatLng
函数中执行相同操作:
The geocode
method makes an asynchonous call and uses a callback to handle the result, so you have to do the same in the codeLatLng
function:
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);
}
});
}
}
这篇关于如何从 Google Maps JavaScript 地理编码器回调返回变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!