在循环中使用时,反向地理编码器无法正常工作

时间:2013-10-17 12:14:47

标签: javascript google-maps geocoding

我的问题是使用Google地图进行反向地理编码。我想对n个(少于15个)纬度和经度坐标进行地理编码,以便我可以使用获得的地址绘制路线。我的问题是当我在循环中使用它时,它没有按照lat-lng坐标的顺序给出地址。循环未正确执行。我遇到问题的代码部分是:

 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);
      }
    }
  });    
 }

获得的地址数组与latlng数组不一致。第二个latlng首先进行地理编码,并且第二个警报框中的i值始终为6(在这种情况下tlength = 6)。它应该从0变为5.但它没有发生。有人可以帮我弄这个吗。或者他们是否有任何其他方式直接使用latlong coorinates绘制路线?

2 个答案:

答案 0 :(得分:1)

地理编码是异步的。无法及时保证回调的顺序。一种解决方法是使用函数闭包将输入索引与回调相关联。请注意,地理编码器受限于配额和速率限制。如果您没有检查返回的状态,您将不知道何时遇到限制。 (如果你的阵列中有很多分数,下面代码中的警报就会变得非常烦人......)

 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);
 }

答案 1 :(得分:0)

您需要在代码中使用此错误:

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);
      }
    }
  });    
 }