-1

I'm a novice and I'm trying to get a Google Apps Script to spit out the country related to a set of latitude and longitude co-ordinates, by hitting the Google Maps Geocoder API and doing a reverse geocode.

So far my function is poor and looks like this:

function reverseGeocode() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheetByName("Output");
 var range = sheet.getRange("A1");

 sheet.setActiveRange(range);

 // Gets the address of a point in London.
 var response = Maps.newGeocoder().reverseGeocode(51.5096, -0.15537);
 for (var i = 0; i < response.results.length; i++) {
   var result = response.results[i];
   range.setValue(result.formatted_address);
     }
 };

At the moment it just spits out the longer formatted address to cell A1. Any idea what I'd have to replace result.formatted_address with to get it to spit out the country?

I think there's an array in the result for address_components.types which has a part called country... but since I'm a novice I don't know how to reference it!

PuGZoR
  • 59
  • 7

1 Answers1

1

Here's a function to extract an address component like "country" given the address_components you mention.

function extractAddressComponent(componentList, componentName) {
  for(var i=0; i<componentList.length; i++) {
  if(componentList[i].types.indexOf(componentName)!=-1) {
    return componentList[i].long_name;
  }
}

}

Inserting in your sample I use:

var country  = extractAddressComponent( result.address_components, "country");
PeterU
  • 76
  • 4