Search code examples
javascriptgoogle-mapsgeolocationreverse-geocoding

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


Let me first give you an example of the data returned after selecting 2 different cities - Tokyo and London.

Tokyo:

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

London:

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

As you can clearly see, the array elements vary based on location, so if I wanted to get the country of Tokyo, I'd select it with:

data.address_components[7].long_name

Sadly this will not work with the case of London's country since the array doesn't even have an element with index of 7. I'm more or less just trying to pass "City, Country" format to my back end but because of those array differences I sometime pass the correct information and sometimes I pass something undesirable.

Am I missing something?


Solution

  • The types array of each component indicates the type of that component (of course!) and will always contain the string 'country' for a country. You can therefore find the correct element in the array based on that. Something like the following should suffice:

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

    This finds the component which has the 'country' type, then takes the long_name of that component.

    Source: Geocoding API Developer Guide