我已经写了一个函数来返回传递给该函数的任何GPS坐标的城镇,但由于某种原因它没有返回城镇。如果我警告镇,它会告诉我正确的城镇。
代码:
function getTown(latitude,longitude){
// Define Geocoding
var geocoder = new google.maps.Geocoder();
// Using the longitude / latitude get address details
var latlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': latlng}, function(results, status){
// If response ok then get details
if (status == google.maps.GeocoderStatus.OK) {
var town = results[1].address_components[1].long_name;
return town; // Returns Norwich when alerted using the e.g below.
}
});
}
示例:
getTown(52.649334,1.288052);
答案 0 :(得分:0)
这是因为你从里面一个嵌套函数返回城镇。对geocoder.geocode的调用是异步的,并且会在经过一段时间后返回。您可以将其设置为如下变量:
var theTown = null;
function getTown(latitude,longitude){
// Define Geocoding
var geocoder = new google.maps.Geocoder();
// Using the longitude / latitude get address details
var latlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': latlng}, function(results, status){
// If response ok then get details
if (status == google.maps.GeocoderStatus.OK) {
var town = results[1].address_components[1].long_name;
theTown = town; // Returns Norwich when alerted using the e.g below.
}
});
}