Javascript 使用谷歌地图API从地址获取国家/地区

Javascript 使用谷歌地图API从地址获取国家/地区,javascript,google-maps,Javascript,Google Maps,我正在用谷歌地图API对一个地址进行地理编码,我需要通过一个给定的地址获取国家名称。这是我的代码: var address = "<?php echo $address;?>"; var raw; function initialize(){ var geocoder = new google.maps.Geocoder(); geocoder.geocode({ "address": address },function(results

我正在用谷歌地图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);
但是所有的返回要么未定义,要么什么也没有。
我只想获取阿根廷并将其存储在一个变量中。

由于对象数组是动态的,因此您必须对其进行迭代:

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

初始化

使用ES6,您可以这样写:

const geocoder = new google.maps.Geocoder();
const address = "1 Infinite Loop, Cupertino, CA";

geocoder.geocode({
    "address": address
}, (raw) => {

    const cities = [...new Set(raw.map(c => c.address_components.filter(
        a => {return a.types.includes("country");}
    )[0].long_name))];

    console.log(cities);
});
说明:

原始-地理编码器返回的对象。它是数组。所以我们通过地图来处理这个问题。 在地图中,我们只按地址中包含国家/地区等类型的这些组件进行过滤。 接下来,我们将此结果转换为设置为“在唯一中生成” 最后我们通过。。。运算符获取字符串的简单数组。
但有时有5个以上的变量,所以可能5就是6,有没有一种方法我不能避免使用它,并以某种方式使用类型[country]来获取国家值?dynamic Objects的编辑答案谢谢,这很有效,我不知道是谁否决了你!
const geocoder = new google.maps.Geocoder();
const address = "1 Infinite Loop, Cupertino, CA";

geocoder.geocode({
    "address": address
}, (raw) => {

    const cities = [...new Set(raw.map(c => c.address_components.filter(
        a => {return a.types.includes("country");}
    )[0].long_name))];

    console.log(cities);
});