繁体   English   中英

使用Google Maps API从地址获取国家

[英]Get country from address with the 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);

控制台返回一个包含数据的数组,我想获取下图所示的国家/地区:

这是控制台返回的内容

我该如何实现? 我尝试过:

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;

但是所有返回“未定义”或什么都不返回的信息。 我只想获取“阿根廷”并将其存储在变量中。

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

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

说明:

  • geocoder返回的原始对象。 它是数组。 因此,我们通过map对此进行了处理。
  • 在地图中,我们仅按地址的这些组成部分(包含国家/地区)进行过滤。
  • 接下来,我们将此结果转换为Set以使其具有唯一性
  • 最后,我们通过...运算符将其传播,以获得简单的字符串数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM