从 Google Sheet 中的地址生成 Google 地图

Generate Google Map from Addresses in Google Sheet

我想创建一个 Google 地图,从 google sheet 中提取地址。我已经想出如何生成单个地址的地图搜索(见下文),但无法弄清楚如何让我的地图绘制多个地址。

 function sendMap2() {
 var sheet = SpreadsheetApp.getActive().getSheetByName('Summary');
 var address = sheet.getRange('C15:C17').getValue();
 var mapUrl = "https://www.google.com/maps/search/?api=1&query=";
 var mapQuery = encodeURIComponent(address);
 GmailApp.sendEmail('emailaddress@gmail.com', 'Map', 'Map Link: '+mapUrl+mapQuery );
}

问题:

您正在使用 getValue,它只会 return 您指定范围内的左上角单元格(即 C15).

解决方案:

如果你想得到范围内的所有地址,你必须使用getValues instead. This will return a two-dimensional array of values, which I'd suggest you to transform to a simple array of addresses. You can then iterate through each address in this array, appending each array to the body of the email message with concat()

可能是以下几行:

function sendMap2() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Summary');
  var values = sheet.getRange('C15:C17').getValues();
  var addresses = [];  
  for (var i = 0; i < values.length; i++) {
    addresses = addresses.concat(values[i]);
  }
  var body = "";
  for (var j = 0; j < addresses.length; j++) {
    var mapUrl = "https://www.google.com/maps/search/?api=1&query=";
    var mapQuery = encodeURIComponent(addresses[j]);
    body = body.concat('Map Link: ' + mapUrl + mapQuery + '\n');
  }
  GmailApp.sendEmail('your-email', 'Map', body);
}

更新:

如果你想在一个 URL 中指向多个地址,你可以改用这个:

  var mapUrl = "https://www.google.com/maps/dir/";
  var body = 'Map Link: ' + mapUrl;
  for (var j = 0; j < addresses.length; j++) {
    var mapQuery = encodeURIComponent(addresses[j]);
    body = body.concat(mapQuery + '/');
  }
  GmailApp.sendEmail('your-email', 'Map', body);
}

参考: