【问题标题】:How to always get city from google geocoding api如何始终从谷歌地理编码 api 获取城市
【发布时间】:2022-01-15 01:12:06
【问题描述】:

我正在使用谷歌地理编码 API,并且正在尝试获取城市。这是我正在获取的信息。

const city = data.results[0].address_components[3].long_name

问题在于响应会根据用户提供的地址而有所不同。在某些情况下,它将位于 address_components[2] 而不是 3。城市在响应中,但在不同的数组中。

有没有办法总能得到城市,不管它在数组中的哪个位置?

【问题讨论】:

    标签: javascript google-api geocoding google-geocoder


    【解决方案1】:

    当然有办法。为了实现这一点,您不应依赖地址组件数组中的确切位置。

    相反,您必须通过“类型”字段应用过滤器来找出城市的相应地址部分。

    可以使用以下数组方法:

    代码截图如下

    const addressComponents = data.results[0].address_components;
    const filteredArray = addressComponents.filter(
        address_component => address_component.types.includes("locality")
    ); 
    const city = filteredArray.length ? filteredArray[0].long_name : "City not found";
    

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多