返回 JavaScript 对象警报“未定义”

returning javascript object alerting "undefined"

本文关键字:未定义 JavaScript 对象 返回      更新时间:2023-09-26

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

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

//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('');
        }
    });
}

希望这有帮助!

我相信

这是一个异步问题。您需要从函数返回 Promise,然后在 Promise 实现时调用警报。

警报

显示未定义的原因是函数尚未完成,因此在显示警报时尚未返回。