GAS 0: Exemplo com apenas 4 linhas de código

Publicado a 10/01/2020, 09:38 por Luis Pitta ‎[org]‎   [ atualizado a 10/01/2020, 10:06 ]

Exemplo prático com GAS: aceder ao G. Slides, Maps e Gmail em apenas 4 linhas de código!


O código:
/** @OnlyCurrentDoc */
function sendMap() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var address = sheet.getRange('A1').getValue();
  var map = Maps.newStaticMap().addMarker(address);
  GmailApp.sendEmail('friend@example.com', 'Map', 'See below.', {attachments:[map]});
}


O código explicado:
  1. This is a normal JavaScript function declaration for sendMap().
function sendMap() {
  1. The first line of code calls the Spreadsheet Service accessible from Apps Script via the SpreadsheetApp object. The returned sheet is assigned to a variable of the same name. The getActiveSheet() method does exactly what it says it does—it returns a "handle" to the current sheet that is active in the user interface (UI).
  var sheet = SpreadsheetApp.getActiveSheet();
  1. With the sheet object, reference the cell range (of a single cell) in A1 notation with getRange(). A "range" is a group of cells, including just a single one like ours... cell A1, the one we entered the address in. Now let's fetch what's inside that range of cells with the getValue() call, and assigned to the address variable upon return. Try adding more addresses and reading from different cells.
  var address = sheet.getRange('A1').getValue();
  1. The 3rd line of code connects to the Google Maps Service via the Maps object. As soon as we have access to the Maps Service, we request a new static map be created via newStaticMap(). You can then put a "pin" dropped on the address we pulled from the Sheet by using the addMarker() method.
  var map = Maps.newStaticMap().addMarker(address);
  1. The last line uses the Gmail Service (via the MailApp object), calling its sendEmail() method, to send the email which includes both the text "See below." and the map image as an attachment.
  GmailApp.sendEmail('friend@example.com', 'Map', 'See below.', {attachments:[map]});
}