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

$( document ).ready(function() {
    $.support.cors = true;
    $.ajaxSetup({ cache: false });
    var city = '';
    var hascity = 0;
    var hassub = 0;
    var state = '';
    var nbhd = '';
    var subloc = '';
	
    $('#zip_code').keyup(function() {
      $zval = $('#zip_code').val();

      if($zval.length == 5){
         $jCSval = getCityState($zval, true); 
      }
    });
  
  function getCityState($zip, $blnUSA) {
	 var date = new Date();
	 $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + $zip + '&key=YOURGOOGLEMAPSAPIKEY&type=json&_=' + date.getTime(), function(response){
         //find the city and state
	 var address_components = response.results[0].address_components;
	 $.each(address_components, function(index, component){
		 var types = component.types;
		 $.each(types, function(index, type){
			if(type == 'locality') {
			  city = component.long_name;
			  hascity = 1;
			}
			if(type == 'administrative_area_level_1') {
			  state = component.short_name;
			}
			if(type == 'neighborhood') {
			  nbhd = component.long_name;
			}
			if(type == 'sublocality') {
			  subloc = component.long_name;
			  hassub = 1;
			}
		 });
	});

	//pre-fill the city and state
        if(hascity == 1){
			$('#city').val(city);
        } else if(hassub == 1) {
            $('#city').val(subloc);
        } else {
	    $('#city').val(nbhd);
	}
	$('#state').val(state);
	  //reset
	var hascity = 0;
	var hassub = 0;
    });
  }
});

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.

  2. Jaswinder says

    Great! Thanks a lot.

  3. Thanks for keeping this up! Had to jump through some hoops to get Google to accept the request. If this can help anyone else, I pasted the raw URL into FireFox Dev Edition and it was able to pass on very specific errors from Google which were invaluable for troubleshooting. Also was able to parse the JSON payload. Pretty cool!

Speak Your Mind

*