在循环内向数组添加元素

时间:2018-12-16 18:34:50

标签: javascript google-apps-script google-sheets

我有以下代码通过选择单元格将一系列邮政编码转换为长纬度,在此示例中为A2:C3

它运作良好,但我希望它要做的就是将范围添加到数组的long和lat项中,然后假设会更快地将数组转回表中。

我尝试过cells.split,但仍然一次只能打印一行。

示例数据,英国邮政编码,其中长和纬度为空单元格

  |     A    |      B     |      C     |
1 | Postcode | Long       | Lat        |
2 | SW1 1AA  |            |            |
3 | EC1V 9BP |            |            |

当前应用脚本

function getGeocodingRegion() {
  return PropertiesService.getDocumentProperties().getProperty('GEOCODING_REGION') || 'uk';
}

function addressToPosition() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var cells = sheet.getActiveRange();

  var addressColumn = 1;
  var addressRow;

  var latColumn = addressColumn + 1;
  var lngColumn = addressColumn + 2;

  var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion());
  var location;

  for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) {
    var address = cells.getCell(addressRow, addressColumn).getValue();

    // Geocode the address and plug the lat, lng pair into the 
    // 2nd and 3rd elements of the current range row.
    location = geocoder.geocode(address);

    // Only change cells if geocoder seems to have gotten a 
    // valid response.
    if (location.status == 'OK') {
      lat = location["results"][0]["geometry"]["location"]["lat"];
      lng = location["results"][0]["geometry"]["location"]["lng"];

      cells.getCell(addressRow, latColumn).setValue(lat);
      cells.getCell(addressRow, lngColumn).setValue(lng);
    }
  }
};

1 个答案:

答案 0 :(得分:1)

由于您对电子表格的每一行都执行了此操作,因此只需对所有行进行getValues(),循环遍历值并构建另一个2D数组,然后使用setValues()将该数组放置在地址列旁边

function addressToPosition() {
  var sheet = SpreadsheetApp.getActiveSheet();

  // Get all values at once, a 2D array with getLastRow() rows and 1 column
  var cells = sheet.getRange(1,1,sheet.getLastRow(),1).getValues();
  var results = [];  // Will build a 2D array for setValues()
  for( var i=0; i<cells.length; i++ ) {
    var location = geocoder.geocode(cells[i][0]);
    if( location.status === "OK" ) {
      // I'm assuming this works, can't test
      var lat = location["results"][0]["geometry"]["location"]["lat"];
      var lng = location["results"][0]["geometry"]["location"]["lng"];
      results.push([lat,lng]);
    }
    else {
      results.push(["",""]); // if status is not OK
    }
  }
  // Now put the results in columns B and C
  sheet.getRange(1,2,results.length,results[0].length).setValues(results);
};