gpt4 book ai didi

javascript - 来自 Google Maps Geocoder v3 的返回地址

转载 作者:行者123 更新时间:2023-11-30 10:50:40 25 4
gpt4 key购买 nike

我有以下功能:

$(function() {
var address = $("#address").text();
var r;

function encodeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[0].geometry.location
r = results[0].geometry.location
console.log("inside:" + r);
} else {
alert("Google Maps had some trouble finding" + address + status);
}
});
}

encodeAddress()
console.log("outside:" + r);
});

我正在尝试返回用于街景和 Gmap 的地理编码地址。内部返回正确的值,外部返回未定义的值。

非常感谢所有帮助,我确实在其他地方读到过不可能以这种方式返回值,但必须向可信赖的 StackOverflow 社区核实。

提前谢谢你。

最佳答案

您可以这样做,并在 Geocode 的回调函数中调用 outputGeo 函数。基本上,您在 Geocode 回调之前访问 r,因此 r 仍未定义:

$(function() {
var address = $("address").text();
var r;

function encodeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[0].geometry.location;
r = results[0].geometry.location;
outputGeo(r);
} else {
alert("Google Maps had some trouble finding" + address + status);
}
});
}

encodeAddress();
function outputGeo(result){
console.log("outside:" + result);
}
});

这里解释了地理编码服务的工作原理。

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.

关于javascript - 来自 Google Maps Geocoder v3 的返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5517120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com