Last active
July 2, 2021 17:14
-
-
Save crismanNoble/730b764e61e76b9235309456ad4b87f3 to your computer and use it in GitHub Desktop.
zip blur
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
$('#zip').blur(function(){ | |
var zip = $(this).val(); | |
var api_key = 'YOUR_API_KEY_HERE'; | |
if(zip.length){ | |
//make a request to the google geocode api with the zipcode as the address parameter and your api key | |
$.get('https://maps.googleapis.com/maps/api/geocode/json?address='+zip+'&key='+api_key).then(function(response){ | |
//parse the response for a list of matching city/state | |
var possibleLocalities = geocodeResponseToCityState(response); | |
fillCityAndStateFields(possibleLocalities); | |
}); | |
} | |
}); | |
function fillCityAndStateFields(localities) { | |
var locality = localities[0]; //use the first city/state object | |
$('#city').val(locality.city); | |
$('#state').val(locality.state); | |
} | |
function geocodeResponseToCityState(geocodeJSON) { //will return and array of matching {city,state} objects | |
var parsedLocalities = []; | |
if(geocodeJSON.results.length) { | |
for(var i = 0; i < geocodeJSON.results.length; i++){ | |
var result = geocodeJSON.results[i]; | |
var locality = {}; | |
for(var j=0; j<result.address_components.length; j++){ | |
var types = result.address_components[j].types; | |
for(var k = 0; k < types.length; k++) { | |
if(types[k] == 'locality') { | |
locality.city = result.address_components[j].long_name; | |
} else if(types[k] == 'administrative_area_level_1') { | |
locality.state = result.address_components[j].short_name; | |
} | |
} | |
} | |
parsedLocalities.push(locality); | |
//check for additional cities within this zip code | |
if(result.postcode_localities){ | |
for(var l = 0; l<result.postcode_localities.length;l++) { | |
parsedLocalities.push({city:result.postcode_localities[l],state:locality.state}); | |
} | |
} | |
} | |
} else { | |
console.log('error: no address components found'); | |
} | |
return parsedLocalities; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment