将地理编码器的位置保存到数组中

Save the location of geocoder into array

本文关键字:保存 数组 位置 编码器      更新时间:2023-09-26

我有一个地址数组(选项卡),我想将所有地址的位置保存到另一个多维(测试)中,我已经尝试过这段代码,但它不起作用

var test = [];
for (var i = tab.length - 1; i >= 0; i--) {
  var r=[];
  geocoder.geocode({address: tab[i].toString()},function (result,status){
    if (status == google.maps.GeocoderStatus.OK) {
      r.push(result[0].geometry.location.k);
      r.push(result[0].geometry.location.D);
    }else{
      r.push(0);
      r.push(0);
    };
  })
  test.push(r);
}

您必须在

地理编码回调中创建/推送临时数组r

var tab   =['berlin','paris','rome'],
    test  =[],
    geocoder=new google.maps.Geocoder();
for (var i = tab.length - 1; i >= 0; i--) {
  
  geocoder.geocode({address: tab[i].toString()},function (result,status){
    var r=[];
    if (status == google.maps.GeocoderStatus.OK) {
      r.push(result[0].geometry.location.lat());
      r.push(result[0].geometry.location.lng());
    }else{
      r.push(0);
      r.push(0);
    };
    test.push(r);
    //print resulting array
    if(test.length===tab.length){
      document.body.textContent='['n ['+test.join('],'n [').toString()+']'n]';
    }
  })
  
}
body{white-space:pre;font-family:monospace;}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>

另请注意:要访问 LatLng 的latlng,请使用具有相似名称的内置方法。属性kD在 API 版本中不稳定。

但是数组方法存在一个问题:不能保证结果按所需顺序到达,您将无法获得地址和返回位置之间的关系。

另一种方法,它使用对象(使用地址作为键):

var tab   ={'berlin':null,'paris':null,'rome':null},
    geocoder=new google.maps.Geocoder();
    
for (var k in tab) {
  
  geocoder.geocode(
     {
        address: k.toString()
     },
     (function(address){
       return function(result,status){
       if (status == google.maps.GeocoderStatus.OK) {
        tab[address]={
                lat:result[0].geometry.location.lat(),
                lng:result[0].geometry.location.lng()
               }
       }
       
       document.body.textContent=JSON.stringify(tab);
      } 
     }(k)));  
}
body{white-space:pre;font-family:monospace;}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>