Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get address components from Google Places API response

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>
like image 447
Sam Avatar asked Jan 05 '16 06:01

Sam


2 Answers

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.

like image 196
spiv Avatar answered Oct 16 '22 19:10

spiv


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

like image 44
m.aibin Avatar answered Oct 16 '22 19:10

m.aibin