Javascript 反向地理编码器在循环中使用时工作不正常
我的问题是使用谷歌地图进行反向地理编码。我想对n号(小于15)的纬度和经度坐标进行地理编码,以便我可以使用获得的地址绘制路线。我的问题是,当我在循环中使用它时,它没有按照传递的lat lng坐标的顺序给出地址。循环未正确执行。我遇到问题的代码部分是:Javascript 反向地理编码器在循环中使用时工作不正常,javascript,google-maps,geocoding,Javascript,Google Maps,Geocoding,我的问题是使用谷歌地图进行反向地理编码。我想对n号(小于15)的纬度和经度坐标进行地理编码,以便我可以使用获得的地址绘制路线。我的问题是,当我在循环中使用它时,它没有按照传递的lat lng坐标的顺序给出地址。循环未正确执行。我遇到问题的代码部分是: for(var i=0;i<tlength;i++){ alert(i); var geocoder = new google.maps.Geocoder(); geocoder.geocode({'latLng': l
for(var i=0;i<tlength;i++){
alert(i);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng[i]},function(results, status) {
alert(i);
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
address.push(add);
}
}
});
}
for(var i=0;i您需要在代码中使用如下错误:
var latlng = new google.maps.LatLng(51.9000,8.4731);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng},function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
//address.push(add);
alert(results[0].formatted_address);
}
}
});
对于您的代码,您需要这样传递:
for(var i=0;i<tlength;i++){
var latlng = new google.maps.LatLng(latlng[i]);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng},function(results, status) {
alert(i);
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
// var add=results[0].formatted_address;
address.push(results[0].formatted_address);
}
}
});
}
用于(var i=0;i地理编码是异步的。回调的顺序不能及时保证。一个修复方法是使用函数闭包将输入索引与回调关联。请注意,地理编码器受配额和速率限制的约束。如果不检查返回的状态,您将不知道何时会遇到限制。(如果阵列中有很多点,下面代码中的警报将变得非常烦人…)
var geocoder=new google.maps.geocoder();
函数反向编码(索引){
geocoder.geocode({'latLng':latLng[index]},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
如果(结果[0]){
var add=results[0]。格式化的\u地址;
地址[索引]=添加;
}else警报(“无“+laglng[指数]”结果);
}else警报(“地理代码失败:+状态);
});
}
对于(var i=0;iGeoCode是异步的。回调的顺序不保证及时。一个修复方法是使用函数闭包将输入索引与回调关联。很抱歉,我没有在此处上载我的全部代码。我使用了'var latlng=new google.maps.latlng(51.9000,8.4731)'在我没有上传到这里的前一行中。还有其他方法吗?谢谢你的回答。不,这是最简单的方法,我不知道是否有。我总是在我的许多应用程序中使用这个方法,即使我在开始时包含了警报框。因为我正在测试一些随机值,所以已经删除了那个部分。你能帮我使用函数cl吗osure您刚才提到过。任何有关函数关闭信息的链接都会对我有很大帮助。谢谢您的回复。我回答中的“reverseGeocode”函数在“index”变量上得到函数关闭。一个参考是。谢谢。这对我帮助很大。现在我的地址正在正确更新。但我收到了一个警报如果我增加点数,“地理编码失败:超过查询限制”。即使我增加点数,是否有其他方法可以使反向地理编码工作?这(达到查询限制)就是反向地理编码(或地理编码)大量点数的问题。最佳解决方案是将地址与坐标存储在数据库中(因此,你不需要使用谷歌的资源将其取回)或者如果你只拥有坐标,则进行反向地理编码“离线”并将结果“缓存”到数据库中(定期刷新以符合服务条款),或者构建自己的反向地理编码器。
var geocoder = new google.maps.Geocoder();
function reverseGeocode(index) {
geocoder.geocode({'latLng': latlng[index]},function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add=results[0].formatted_address;
address[index] = add;
} else alert("no results for "+laglng[index]);
} else alert("Geocode failed: "+status);
});
}
for(var i=0;i<tlength;i++){
reversGeocode(i);
}