Skip to content

Instantly share code, notes, and snippets.

@jenikm
Last active January 27, 2017 02:51
Show Gist options
  • Save jenikm/c0fa8552bf39bf4bc70f76ce91997274 to your computer and use it in GitHub Desktop.
Save jenikm/c0fa8552bf39bf4bc70f76ce91997274 to your computer and use it in GitHub Desktop.
Google script postal code resolver
function get_postal_code(street, city, state){
var cache_seconds = 60 * 60 * 24 * 365 // cache for 1 year
var address = [street, city, state, "United States"].join(", ")
var cache = CacheService.getScriptCache();
var cached = cache.get(address);
if (cached != null) {
return cached;
}
var randnumber = Math.random()*5000;
Utilities.sleep(randnumber);
var response = Maps.newGeocoder().setRegion('com').geocode(address);
if (response.status === "OK") {
//Logger.log("response " + JSON.stringify(response));
try{
var postal_code = response.results[0].address_components.filter(function(a){ return a.types.indexOf("postal_code") != -1})[0].short_name
cache.put(address, postal_code, cache_seconds);
return postal_code
}
catch(e){
Logger.log(e)
cache.put(address, "", cache_seconds);
return ""
}
}
else {
return "error";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment