Google Geocoding -- parsing address_components that may return differently

Atticus picture Atticus · Jun 10, 2011 · Viewed 9k times · Source

I'm using Google Maps V3 api. I am submitting an address search to return the proper geocoded result including the address, name of establishment, and lat/lngs.

My problem is that the response from the geocoder can be formatted differently. It always follows the same structure, but some responses use different keys for the address_components data structure.

For Example, some searches result in:

establishment               -> location name
street_number               -> address street number
route                       -> the street name
locality                    -> the city
administrative_area_level_1 -> the state
postal_code                 -> zip/postal code

whereas, if i were to search a general area, such as "Hampton Beach, NH" i would receive:

sublocality                 -> beach name / area
administrative_area_level_3 -> city/town name
administrative_area_level_1 -> the state
postal_code                 -> zip/postal code

as you can see the two responses have their differences. Is there a known jquery library that can be used to handle these different responses to return a data set of the address components that can be used for a human-readable way?

I will note that the response also returns a "formatted_address" type, which returns it like: "Hampton Beach, NH 03842, USA" OR "Boston University, 1 University Rd, Boston, MA 02215-1407, USA" As you can see, these too are pretty different. I could split by comma, but I'd like to use the actual address_components for a flawless database insert.

Answer

Jason Gennaro picture Jason Gennaro · Jun 13, 2011

Why not have your DB mirror only the following keys?

street_number                    -> address street number
route                            -> the street name
locality                         -> the city/town    
administrative_area_level_3      -> the city/town
administrative_area_level_1      -> the state
postal_code                      -> zip/postal code

Where a locality exists, use that in your request (as it appears to deliver the more detailed info - http://code.google.com/apis/maps/documentation/geocoding/#JSON )

Where no street name or locality exists, request administrative_area_level_3 and administrative_area_level_1

This would provide you with a full human-readable postal address when the info exists or just the city/state for a sublocality (e.g. beach), as you mentioned in one of the comments.

**I'm assuming you only care about the US.