2015-12-20 184 views
-1

我使用Google Maps API对地址进行地理编码,我需要通过给定地址获取国家/地区名称。这是我的代码:使用Google Maps API获取国家/地区地址

var address = "<?php echo $address;?>"; 
var raw; 

function initialize(){ 

    var geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 
     "address": address 
    },function(results){ 
     raw = results[0].address_components; 
     console.log(raw); 
    }); 

} 

google.maps.event.addDomListener(window, 'load', initialize); 

控制台返回数据数组,我想全国下面的图像所见:

Here's what the console returns

我怎样才能做到这一点?我试过:

raw = results[0].address_components.types["country"]; 

raw = results[0].address_components.types; 

raw = results[0].address_components.country; 

raw = results[0].address_components.types.long_name; 

但是,所有返回“undefined”或什么都没有。 我只想获得“阿根廷”并将其存储在一个变量中。

回答

3

由于对象的数组是动态的,你必须来遍历它:

var raw; 
var address = "1 Infinite Loop, Cupertino, CA" 

function initialize(){ 
    var geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 
     "address": address 
    },function(results){ 
     raw = results; 
     //find country name 
     for (var i=0; i < results[0].address_components.length; i++) { 
      for (var j=0; j < results[0].address_components[i].types.length; j++) { 
      if (results[0].address_components[i].types[j] == "country") { 
       country = results[0].address_components[i]; 
       console.log(country.long_name) 
       console.log(country.short_name) 
      } 
      } 
     } 
    }); 
} 

初始化();

+2

但是有时候有超过5个变量,所以也许5就是6,有没有办法避免使用这种方式,并以某种方式使用类型[“国家”]来获得国家价值? –

+0

动态对象的编辑答案 –

+1

谢谢,那工作,我不知道谁低估了你! –

相关问题