Javascript 谷歌地图地理编码位置不返回城镇
我编写了一个函数,用于返回传递给该函数的任何GPS坐标的城镇,但由于某些原因,它不会返回城镇。如果我通知镇上,它会告诉我正确的镇 代码:Javascript 谷歌地图地理编码位置不返回城镇,javascript,google-maps,Javascript,Google Maps,我编写了一个函数,用于返回传递给该函数的任何GPS坐标的城镇,但由于某些原因,它不会返回城镇。如果我通知镇上,它会告诉我正确的镇 代码: function getTown(latitude,longitude){ // Define Geocoding var geocoder = new google.maps.Geocoder(); // Using the longitude / latitude get address details var la
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);
示例:
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);
这可能是因为您是从嵌套函数中返回的。对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.
}
});
}
如果您希望运行
var town=getTown(52.649334,1.288052),那么这没有什么区别代码>并将城镇设置为诺维奇,这根本不会发生。调用geocoder.geocode
需要时间。多少时间?每次你调用这个方法时,它都会有所不同,但当你通过互联网发送请求从谷歌获取一些数据时,可能需要几百毫秒。您正在使用,这是编程任务中的一个重要概念。为什么我可以立即提醒它而不返回它?它不是真正的“立即”,只是速度非常快(~100ms),而且绝对不是带内函数返回。它正在后台发出HTTP请求。打开开发人员控制台,如Firebug或Chrome开发人员控制台,并查看网络选项卡。你会看到请求发出并返回。嗯,我不知道该怎么办,你能找到解决问题的方法吗,或者知道其他解决方案吗?