Skip to content

Instantly share code, notes, and snippets.

@hkdeven
Last active April 4, 2018 17:10
Show Gist options
  • Save hkdeven/c9814f90514ebbd10b36c7f8136b9527 to your computer and use it in GitHub Desktop.
Save hkdeven/c9814f90514ebbd10b36c7f8136b9527 to your computer and use it in GitHub Desktop.
County and State lookup using Zipcode with the help of the Google Maps Geocoding API.
<!DOCTYPE html>
<html lang="en">
<head>
<title>County and State Lookup w/ Google Maps Geocoding API</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<script language="javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<body>
<div class="container">
<h2>Search for County and State using Zipcode</h2>
<form>
<label>zip:</label> <input type="text" name="zip"><a href="#" onclick="getLocation()">Get Address</a>
</form>
</div>
<script language="javascript">
function getLocation(){
getAddressInfoByZip(document.forms[0].zip.value);
}
function response(obj){
console.log(obj);
}
function getAddressInfoByZip(zip){
if(zip.length >= 5 && typeof google != 'undefined'){
var addr = {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zip }, function(results, status){
if (status == google.maps.GeocoderStatus.OK){
if (results.length >= 1) {
for (var ii = 0; ii < results[0].address_components.length; ii++){
var street_number = route = street = city = state = county = zipcode = country = formatted_address = '';
var types = results[0].address_components[ii].types.join(',');
if (types == 'administrative_area_level_1,political'){
addr.state = results[0].address_components[ii].short_name;
}
if (types == 'administrative_area_level_2,political'){
addr.county = results[0].address_components[ii].short_name;
nameWithoutCountyAppended = addr.county.split(' County');
addr.county = nameWithoutCountyAppended;
}
}
addr.success = true;
for (name in addr){
alert(name + ': ' + addr[name]);
}
response(addr);
} else {
response({success:false});
}
} else {
response({success:false});
}
});
} else {
response({success:false});
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment