Skip to content →

Doing some useful things with Maps in Google Apps Script

At the NCSU Apps Script Hackathon, a bunch of people were trying to do things in Google Apps Script with Google Maps. There were tons of great use cases for this. One developer wanted to pull a feed of all Groupon deals, and display their locations on a map so that the user could quickly and easily browse the closest ones.

Although the documentation is a bit on the sparse side, the maps API in Apps Script is pretty capable. It essentially generates a static image of a map, with various features you give it. But there are some nice things you can do prior to generating the image.

Here is a quick function to generate and show a map with two markers, and then display that map in a dialog to the user.

:::javascript
function generateMap() {
  var address = "111 8 Ave., New York, NY 10011";
  var mapUrl = Maps.newStaticMap()
      .setMarkerStyle(Maps.StaticMap.MarkerSize.MID,
                      Maps.StaticMap.Color.RED,
                      "A")
      .addMarker(address)
      .setMarkerStyle(Maps.StaticMap.MarkerSize.MID,
                      Maps.StaticMap.Color.RED,
                      "B")
      .addMarker("17 st and 8 ave, new york, ny")
      .setCenter(address)
      .setSize(500, 500)
      .getMapUrl();
  var ui = UiApp.createApplication();
  ui.setTitle("Map");
  var panel = ui.createFlowPanel()
      .setSize("500px", "500px");
  panel.add(ui.createImage(mapUrl));
  ui.add(panel);
  ui.setHeight(500);
  ui.setWidth(500);
  SpreadsheetApp.getActiveSpreadsheet().show(ui);
}

This is nice because you could populate those markers in a variety of ways. If you have a spreadsheet full of location information (do you work for a real estate or delivery company?) then this would make a great feature to add to your company’s spreadsheets. You also get some pretty powerful address matching from Google Maps, in case you don’t have a complete address each time.

If you run the above function, you get this:

Result of generateAndShowMap()

Another problem some developers tried to solve was determining the timezone of an address based on the latitude and longitude of the address. This is also something the maps API can give you, but again the documentation is a little sparse.

Taking the previous example, here we get the latitude and longitude in two lines of code:

:::javascript
function getLatitudeLongitude() {
  var geocode = Maps.newGeocoder()
      .geocode("111 8 ave, new york, ny 10011");
  // See http://goo.gl/5mr1N for reference
  Logger.log(geocode.results[0].geometry.location);
}

There you can see that we created a geocoder from the maps API, and pulled the latitude and longitude for the given address.

There is a lot more you can do, and the Maps portion of Apps Script is documented in the reference guide.

Published in Uncategorized