Best way to get address components from Google Places API response
Asked Answered
R

5

9

I'm implementing Google Places in a form where the user will enter his/her location. The location can be a full address or just a city.

I want to get each individual component of the address the user has provided. What's the best way to get each component i.e. address, city, state, zip code and country.

In the code below, I'm getting the components which appears to be an array. Do I have to loop through it or is there a direct way for me to access each component?

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('location'));
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var components = place.address_components;


            });
        });
</script>
Reinwald answered 5/1, 2016 at 6:6 Comment(0)
I
13

Looping is probably the simplest. There's no direct way to jump straight to the e.g. the state address component (if there is one present), it's a simple array.

You could also process the array into something that allows the direct lookups by type:

var components_by_type = {};
for (var i = 0; i < place.address_components.length; i++) {
  var c = place.address_components[i];
  components_by_type[c.types[0]] = c;
}

console.log(components_by_type['state'].short_name);

That will get a little more complicated if you want to handle more than the first type in each component, though.

Interpolate answered 7/1, 2016 at 7:9 Comment(1)
This maybe out of date, there is no "state" as a type. For type there is only "administrative_area_level_1" and "political" when I lookup addresses and drill down into the address_components.Egg
D
1

Look here for the example from google:

var address = '';
    if (place.address_components) {
      address = [
        (place.address_components[0] && place.address_components[0].short_name || ''),
        (place.address_components[1] && place.address_components[1].short_name || ''),
        (place.address_components[2] && place.address_components[2].short_name || '')
      ].join(' ');
}

This is function to create: Vancouver Greater Vancouver BC (from the link below).

So you can directly access each of the place.address_components as in array. And then do what you want to do. Here is link to this example: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete

Disorganize answered 5/1, 2016 at 6:14 Comment(0)
G
0

From place.address_components you will get array of addresses components so you can get separated from array index in following order:

let postalCode =  place.address_components[place.address_components-1]>

let countryName =  place.address_components[place.address_components-2]

let stateName =  place.address_components[place.address_components-3]

let districtName = place.address_components[place.address_component-4]

let cityName  place.address_components[place.address_components-5]

and so on...

Grasmere answered 13/4, 2022 at 10:24 Comment(1)
Not really. address_components could have different length, for example italian addresses have 8 indexes, french 7Beckner
B
0

I see that different countries in the world have different keys and length, so I just decided to filter the array this way:

streetName = place.address_components.find(o => o.types.includes('route'))?.long_name
Beckner answered 4/7, 2022 at 16:11 Comment(0)
D
0

The simplest way to get address components is using a simple reduce function to avoid multiple loops, e.g using TypeScript:

export type PlaceDetails = {
  streetaddress: string;
  country: string;
  city: string;
  state: string;
  zipCode: string;
}

export type AddressComponent = {
  long_name: string;
  short_name: string;
  types: Array<string>;
}

export async function getPlaceDetails (placeId: string): Promise<PlaceDetails> {
  // Get Place Details using Google Places API
  const details = await getDetails({ 
    placeId,
    fields: ["formatted_address", "name", 'address_component'],
  });
  const addressComponents: Array<AddressComponent> = details.address_components ?? [];
  const result = addressComponents.reduce((acc, component) => {
    if (component.types.includes('locality')) {
      acc.city = component.long_name;
    } else if (component.types.includes('administrative_area_level_1')) {
      acc.state = component.long_name;
    } else if (component.types.includes('country')) {
      acc.country = component.long_name;
    } else if (component.types.includes('postal_code')) {
      acc.zipCode = component.long_name;
    } 
    return acc;
  }, {
    country: '',
  } as PlaceDetails);
  const formattedAddress: string = details.formatted_address ?? '';
  const [street] = formattedAddress.split(',');
  result.streetaddress = street || details.name;
  return result;
}

Hope this can help and happy coding!

Daub answered 5/10, 2022 at 5:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.