返回 JavaScript 对象警报“未定义”
returning javascript object alerting "undefined"
我提前道歉,因为我觉得这是一个如此简单的问题,但我是新手,所以我不太明白该怎么做!
我正在对地址进行地理编码并返回坐标:
//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 实现时调用警报。
警报显示未定义的原因是函数尚未完成,因此在显示警报时尚未返回。
相关文章:
- 行末尾未定义Javascript
- 未定义Javascript文档
- 未定义Javascript函数
- define未定义Javascript节点
- 未定义Javascript对象Class错误
- 全局变量从事件侦听器中变得未定义 - javascript
- 未定义 JavaScript 数组
- Firefox 中的“未定义”JavaScript 错误
- 使用 kineticjs 的未定义 JavaScript 变量
- 为什么我的类在运行时未定义.Javascript 模块模式
- 事件未定义 JavaScript Firefox (JSON)
- 未定义 Javascript 函数
- 未捕获的引用错误 函数未定义 Javascript
- 使用单击处理程序时出现“系统未定义”JavaScript 错误
- 未定义 JavaScript 原型方法
- 如果你不返回任何内容,为什么函数会返回未定义?Javascript
- 未定义Javascript Integer对象
- 未定义Javascript对象
- 与异步和同步函数相关的未定义javascript函数的问题
- 未定义Javascript类构造函数