Created
January 21, 2019 22:07
-
-
Save simonds/f706a22450e03f14880c12193c3d8b9a to your computer and use it in GitHub Desktop.
Automatic City Lookup with Google's Location API (from https://nobleintentstudio.com/blog/zip-code-to-city-state-lookup/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Zipcode Lookup Demo</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.js"></script> | |
<style> | |
input, label, select { | |
display: block; | |
width: 100%; | |
margin: 0; | |
width: 150px; | |
} | |
body { | |
background-color: #eee; | |
} | |
</style> | |
</head> | |
<body> | |
<p>Enter your zipcode and watch the city and state appear magically!</p> | |
<form> | |
<label for="zip">Zip:</label> | |
<input id="zip" name="zip"/> | |
<label for="city">City:</label> | |
<div id="city_wrap"><input id="city" name="city"/></div> | |
<label for="state">State:</label> | |
<input id="state" name="state"/> | |
</form> | |
<p><a href="http://kovalent.co/blog/zip-code-to-city-state-lookup">Read more at the Kovalent blog.</a></p> | |
<script> | |
$(document).ready(function(){ | |
//when the user clicks off of the zip field: | |
$('#zip').keyup(function(){ | |
if($(this).val().length == 5){ | |
var zip = $(this).val(); | |
var city = ''; | |
var state = ''; | |
//make a request to the google geocode api | |
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+zip) | |
.success(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; | |
} | |
if(type == 'administrative_area_level_1') { | |
state = component.short_name; | |
} | |
}); | |
}); | |
//pre-fill the city and state | |
var cities = response.results[0].postcode_localities; | |
if(cities) { | |
//turn city into a dropdown if necessary | |
var $select = $(document.createElement('select')); | |
console.log(cities); | |
$.each(cities, function(index, locality){ | |
var $option = $(document.createElement('option')); | |
$option.html(locality); | |
$option.attr('value',locality); | |
if(city == locality) { | |
$option.attr('selected','selected'); | |
} | |
$select.append($option); | |
}); | |
$select.attr('id','city'); | |
$('#city_wrap').html($select); | |
} else { | |
$('#city').val(city); | |
} | |
$('#state').val(state); | |
}); | |
} | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment