Skip to content

Instantly share code, notes, and snippets.

@pjhoberman
Created August 25, 2014 22:01
Show Gist options
  • Select an option

  • Save pjhoberman/91939b449a7dac9bd2df to your computer and use it in GitHub Desktop.

Select an option

Save pjhoberman/91939b449a7dac9bd2df to your computer and use it in GitHub Desktop.
Google Sheets Lat/Lng Reverse Geocoder
function getAddressData(placeCoord, result, location) {
var r = result === "" ? "" : "&result_type=" + result;
var l = location === "" ? "" : "&location_type=" + location;
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + placeCoord + "&key=APP_KEY" + l + r;
var response = UrlFetchApp.fetch(url);
var json = JSON.parse(response);
return json;
}
function getAddress(placeCoord) {
// Return Address by placeCoord (reverse geocoding) placeCoord=lat,lng
// placeCoord = "39.7391536,-104.9847034";
if (placeCoord == "") {
return "-";
}
var result_type = "",
location_type = "",
city = "", state = "", country = "";
var json = getAddressData(placeCoord, result_type, location_type);
if (json.results[0].address_components[0].long_name == undefined) {
// this means the result was totally blanks.. right?
json = getAddressData(placeCoord, "political", "ROOFTOP");
}
var address = json.results[0].address_components;
//return address[3].types;
for(var i=0; i<address.length; i++){
var stringified = JSON.stringify(address[i].types);
if(stringified == JSON.stringify([ "locality", "political" ])) {
city = address[i].long_name;
}
else if (stringified == JSON.stringify([ "administrative_area_level_1", "political" ])){
state = address[i].short_name;
}
else if (stringified == JSON.stringify([ "country", "political" ])){
country = address[i].long_name;
}
else {
// do something?
}
}
return [city, state, country];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment