gpt4 book ai didi

Javascript 函数返回未定义而不是数字

转载 作者:行者123 更新时间:2023-11-28 11:38:05 24 4
gpt4 key购买 nike

我有两个 Javascript 函数尝试使用 Google Maps API 地理编码查找地址的纬度和经度:

function getLatLon(address) {
var location = -1;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
location = new Array(lat, lon);
//document.getElementById('results').innerHTML = location[0];
} else {
alert("Geocode was not successful.");
}
});
return location;
}

function search() {
var address = document.getElementById('address').value;
var location = getLatLon(address);
document.getElementById('results').innerHTML = location[0];
}

虽然 getLatLon() 内的 location[0] 打印出 #results div 中的正确数字,但 search() 内的 location[0] 返回未定义。您知道为什么会发生这种情况吗?我尝试从 getLatLon() 返回一个纯字符串(“Hello”),效果很好。

最佳答案

问题是 geocoder.geocode(...)异步,因此您无法返回值。尝试像这样:

function getLatLon(address, callback) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
location = new Array(lat, lon);
callback(location);
} else {
alert("Geocode was not successful.");
}
});
}

function search() {
var address = document.getElementById('address').value;
getLatLon(address, function(location) {
document.getElementById('results').innerHTML = location[0];
});
}

关于Javascript 函数返回未定义而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13558462/

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