Google 地图的反向地理编码 returns 数组,对于不同的城市和位置具有不同的大小。我该如何猜测选择哪个数组

Google maps' reverse-geocoding returns arrays with different sizes for different cities and locations. How am I supposed to guess which array to pick

首先让我举一个例子,在 selecting 2 个不同的城市 - 东京和伦敦后返回的数据。

东京:

address_components: Array(9)
0: {long_name: "日本ドクターズビル", short_name: "日本ドクターズビル", types: Array(1)}
1: {long_name: "22", short_name: "22", types: Array(1)}
2: {long_name: "3", short_name: "3", types: Array(3)}
3: {long_name: "4 Chome", short_name: "4 Chome", types: Array(3)}
4: {long_name: "Kudankita", short_name: "Kudankita", types: Array(3)}
5: {long_name: "Chiyoda-ku", short_name: "Chiyoda-ku", types: Array(2)}
6: {long_name: "Tōkyō-to", short_name: "Tōkyō-to", types: Array(2)}
7: {long_name: "Japan", short_name: "JP", types: Array(2)}
8: {long_name: "102-0073", short_name: "102-0073", types: Array(1)}
length: 9

伦敦:

address_components: Array(7)
0: {long_name: "141", short_name: "141", types: Array(1)}
1: {long_name: "Drury Lane", short_name: "Drury Ln", types: Array(1)}
2: {long_name: "London", short_name: "London", types: Array(1)}
3: {long_name: "Greater London", short_name: "Greater London", types: Array(2)}
4: {long_name: "England", short_name: "England", types: Array(2)}
5: {long_name: "United Kingdom", short_name: "GB", types: Array(2)}
6: {long_name: "WC2B 5TA", short_name: "WC2B 5TA", types: Array(1)}
length: 7

如您所见,数组元素因位置而异,因此如果我想获得东京所在的国家/地区,我会select它:

data.address_components[7].long_name

遗憾的是,这不适用于伦敦国家的情况,因为该数组甚至没有索引为 7 的元素。我或多或少只是想将 "City, Country" 格式传递给我结束,但由于这些数组差异,我有时会传递正确的信息,有时会传递一些不需要的信息。

我是不是漏掉了什么?

每个组件的 types 数组指示该组件的类型(当然!)并且将始终包含一个国家/地区的字符串 'country'。因此,您可以基于此在数组中找到正确的元素。像下面这样的东西就足够了:

const country = address_components.find((component) =>
  component.types.includes('country')
).long_name;

这会找到具有 'country' 类型的组件,然后获取该组件的 long_name

来源:Geocoding API Developer Guide