gpt4 book ai didi

javascript - 返回 javascript 对象警报 "undefined"

转载 作者:行者123 更新时间:2023-11-30 16:14:19 25 4
gpt4 key购买 nike

我提前道歉,因为我觉得这是一个如此简单的问题,但我是新手,所以我还不太明白该怎么做!

我正在对地址进行地理编码并返回坐标:

//Geocoder
var geocoder = new google.maps.Geocoder();

//Submit listener and alert the coordinates
submit.addEventListener('click', function() {
alert(geocodeAddress(geocoder, map)));
});

//Geocodes an address and returns the lat lng
function geocodeAddress(geocoder, resultsMap) {
geocoder.geocode({address: address.value}, function(addressLatLng, status) {

//Checks if status returned was ok
if (status === google.maps.GeocoderStatus.OK) {

//adds pin to map and centers map on pin
resultsMap.setCenter(addressLatLng[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: addressLatLng[0].geometry.location
});
//alert(addressLatLng[0].geometry.location);
return(addressLatLng[0].geometry.location);
} else {
alert('No address was found, please try again!');
}
});
}

如果我在函数内部提醒他们,它会正确提醒他们(即 {20.12345, 20.12345})。如果我在提交按钮上提醒他们,它只会说“未定义”。我如何正确返回这些坐标?(我最终必须对他们做点什么,而不仅仅是提醒他们)谢谢!

最佳答案

这应该可行

//Geocoder
var geocoder = new google.maps.Geocoder();

//Submit listener and alert the coordinates
submit.addEventListener('click', function() { //This is callback
geocodeAddress(geocoder, map, function(loc){
alert(loc || 'No address was found, please try again!');
});
});

//Geocodes an address and returns the lat lng
function geocodeAddress(geocoder, resultsMap, cb) {
geocoder.geocode({address: address.value}, function(addressLatLng, status) {

//Checks if status returned was ok
if (status === google.maps.GeocoderStatus.OK) {

//adds pin to map and centers map on pin
resultsMap.setCenter(addressLatLng[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: addressLatLng[0].geometry.location
});
//call cb with location details
cb(addressLatLng[0].geometry.location);
} else {
//call the callback with empty value
cb('');
}
});
}

希望这对您有所帮助!

关于javascript - 返回 javascript 对象警报 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753607/

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