Using geocoding APIs from Apps Script

42 views
Skip to first unread message

Doug Rinckes

unread,
Mar 29, 2019, 5:00:06 AM3/29/19
to open-location-code EXTERNAL
Hi all,

Google Apps Script provides a Geocoder object that you can use in scripts to geocode addresses, or reverse geocode latitude and longitudes. The responses include plus codes, so this means that if you have a bunch of locations, or street addresses, you can easily get the plus codes.

This API isn't charged, and the use is free. There are some limits on the usage (I think it's these).

I'm intending to add this functionality to the Sheets add-on, but in the meantime, here are some instructions I wrote up:

You can use the Apps Script Geocoder class to geocode addresses - the responses may include a plus code. If they don't, you can either use the add-on to convert the locations to a plus code, or, you can use the reverseGeocode method of the Geocode class to get the plus code address. I've put together an example for you.

You can paste the code below into an Apps Script (from a sheet, select Tools > Script Editor). Once you've done that, you can use it like this:

Screenshot from 2019-03-27 18-04-03.png

It will return the formatted street address and the plus code addresses into your sheet like this:

Screenshot from 2019-03-27 18-04-40.png

Let us know if this works for you! Here's the code:

function addressToPlusCode(address) {
  var geocoder = Maps.newGeocoder();
  var response = geocoder.geocode(address);
  var results = [];
  
  // Add each result to the map and doc.
  for (var i = 0; i < response.results.length && i < 9; i++) {
    Logger.log(response.results[i]);
    var result = response.results[i];
    // A plus code might be included in the geocoding result.
    if (result.plus_code) {
      var pc = result.plus_code.compound_code ? result.plus_code.compound_code : result.plus_code.global_code;
      Logger.log('Got plus code from geocode result');
      results.push([result.formatted_address, pc]);
      continue;
    }
    // Try reverse geocoding the result lat/lng to get the plus code.
    var reverse = geocoder.reverseGeocode(result.geometry.location.lat, result.geometry.location.lng);
    if (reverse.plus_code) {
      var pc = reverse.plus_code.compound_code ? reverse.plus_code.compound_code : reverse.plus_code.global_code;
      Logger.log('Got plus code from reverse geocode result');
      results.push([result.formatted_address, pc]);
      continue;
    }
    Logger.log('No plus code :-(');
    results.push([result.formatted_address, null]);
  }
  return results;
}


Ngā mihi,
Doug Rinckes, Technical Program Manager, Google Switzerland GmbH; 9G8F+6W Zürich
Reply all
Reply to author
Forward
0 new messages