我正在开发一个应用程序,我需要从地理编码文本地址派生的console.log地理坐标。我在javascript中编写了以下代码:
var geocoder = new google.maps.Geocoder();
function address_to_coordinates(address_text) {
var address = address_text;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
console.log(address_to_coordinates('London'));
出于某种原因,它打印出未定义的'在控制台。有没有人看到它的原因?
答案 0 :(得分:0)
您需要使用回调
var geocoder = new google.maps.Geocoder();
function address_to_coordinates(address_text, callback) {
var address = address_text;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
address_to_coordinates('London', function(location){
console.log(location);
});