Get City and State from Zip Code with Google Geocoding API

People already don’t like filling out forms so keeping the forms as short and simple as possible is key to getting higher conversion rates. Addresses are one area where we can simplify the forms with a little help from the Google Maps Geocoding API. This API makes it possible for us to easily grab a city and state from zip code data entered in the form.

Google Maps Geocoding API

You’ll need to get your own API Key to utilize the Google Maps API. You can get your own key here. Once you get your key your will just need to stick it in the code snippet provided below in place of the ‘YOURGOOGLEMAPSAPIKEY’ text.

The Geocoding API service is free up to 2,500 requests per day, which will be fine for most and additional costs past that if you need it are very reasonable. You can check out a cost estimator on their Pricing and Plans page.

Code to get the City and State from Zip Code

The code above can be dropped in as-is once you you add your own API key into it. This assumes that you have a form created with fields that have ID’s of “zip_code”, “city”, and “state” for the corresponding fields. You can name the fields anything you want, but just make sure that the jQuery selectors in the code are updated to reflect the field ID’s used.

The code snippet consists of two main pieces of functionality. First is just binding the zipcode field to keystrokes so that we run a check every time something is typed into it. Once the entered text gets to a length of 5 characters we call the custom function. That custom function is part two. It takes the entered zipcode and utilizes the Google Maps Geocoding API to return a bunch of data in JSON format. From that set of data we extract the city and state that are associated with that zip code and enter them into the city and state hidden fields. It all happens in an instant. Ideally, you’ll have some validation on the zipcode field to prevent letters and other extraneous characters from being entered as well.

Demo

Try it out for yourself below. Normally the city and state fields would be set as hidden fields that submit when the form is submitted, but I have them visible here just so you can see what is going on.

Enter Zipcode:
City:

State:

This is just one thing that you can do with the Google Maps API, but there are a lot more possibilities out there to play around with. There are also a lot more pieces of data in the JSON that gets returned with this API call we just used, so you could always expand upon the city and state to also pull in something like county or country. Give it a try!

Comments

  1. Vincent,
    You saved almost 3 hours of my time.

    Thanks.

Speak Your Mind

*