How to parse google maps Address components. (geocoder response)

Ahmed Ali Thabet
2 min readJan 24, 2019

--

google maps geocoder is a really good solution to get an address from latitude, longitude or from google maps autocomplete.

the main problem with it is that it returns an array of address components that we can’t parse exactly. for example, if we made a request like that:-

right there it may seem a fair response but it’s not like this all the time, the name of the city can be in different types, mmmm let’s say that we want the response to be like this as we can see here. https://developers.google.com/maps/documentation/geocoding/intro#Types

so we can loop over the address components array one by one and detect it types so if it’s a “street_address” we can store it in our home and if it’s an “administrative_area_level_3”, “administrative_area_level_2” or an “administrative_area_level_1” it can be our region. but we only need to make an only for loop without too many if statements and we need also to make it choose which one is better so if there an “administrative_area_level_1” and level_2 we need to choose level_1 because it’s a higher level than level_2.

hint: google also helps us with that: it gives us a sorted array so level_2 is before level_1.

and here is the code which we can use to do this.

it’s really simple to reuse it in javascript ( you have only to pass the address_components array from the results of the response of Google maps geocoder API)

getAddressObject(results[0].address_components);

Say Hello on Twitter.

“Hello”

--

--