I was yesterday working with a colleague at Imbibe on a mapping platform which involved sending lookup requests to Google Maps Geocoding api and processing the response results to perform an overlap approximation to figure out whether the result areas were serviceable by the partners of the platform (we had every partner’s serviceable radius from the partner’s location and needed to figure whether a user’s location fell inside a partner’s serviceable polygon). As we worked on the logic, it seemed some partners actually served geographical areas (e.g. an entire city or a postal code) which was not very convenient to express as a serviceable polygon. Rather we needed to check whether the location returned by the geocoding api matched the city or postal code or state/province etc. to figure whether the location was serviceable by the partner.

I expected the geocoding api response to give me address components (e.g. street address, city etc). However Google api’s representation of these (as locality / administrative_area etc) although made sense from the api’s perspective which had to represent hugely diverse nomenclature used for geographical limits; it made it a bit difficult for us to accurately write our logic for country vs province vs city vs postal code vs a polygon overlap search.

What we really needed was a simple parser for the full address (returned as formatted_address by the geocoder) splitting it up into street address / city / province / postal code and country. How difficult it could be I thought, there must be another Google api or a third-party api providing such parsing. To my surprise, I found none from Google and expensive paid apis from third-parties.

So we took it on ourselves to write such a parser for us. And in a very brief coding session, we came up with the following that worked for almost all of our use cases.:

Here’s a sample invocation of the method and the result returned:

The method works for partial addresses too, here are some examples:

NOTE: The method here assumes the postal codes are all numerics (which is true for many but not all countries). Our target audience had only numeric postal codes, so the method worked fine for our needs. However if your audience resides in a country like Canada where postal codes are alpha-numeric, you would only need to change the regex in fnIsPostalCode method and the rest of the logic should still work fine for your needs.

Hope this helps someone…

Share this: