javascriptgoogle-apigeocodinggoogle-geocoder

How to always get city from google geocoding api


I'm using the google geocoding API and I'm trying to get the city. This is I'm getting the info.

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

The issue with this is that the response will be different depending on the address the user gives. In some, it will be in address_components[2] instead of 3. The city is in the response but in a different array.

Is there a way to always get the city regardless of where in the array it is?


Solution

  • Sure there is a way. In order to achieve this you shouldn't rely on the exact position in the address components array.

    Instead you have to apply filter by the "types" field to find out the corresponding address component of the city.

    The following array methods can be used:

    The code snapshot is the following

    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";