我提前道歉,因为我觉得这是一个很简单的问题,但我是新的,所以我不太明白该怎么做!
我正在对地址进行地理编码,然后返回坐标:
//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}。如果我在提交按钮上提醒他们,它只是说"未定义。"我如何正确返回那些坐标?(我最终必须对它们做些什么,而不仅仅是警告它们)谢谢!
答案 0 :(得分:2)
这应该有效
//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('');
}
});
}
希望这有帮助!
答案 1 :(得分:0)
我认为这是一个异步问题。您需要从函数返回Promise,然后在履行承诺时调用警报。
警报显示未定义的原因是因为该功能尚未完成,因此在显示警报时尚未返回。