在 Google 工作表脚本中创建自定义函数以使用 "ArrayFormula"

Make a custom function in Google sheets script to work with "ArrayFormula"

下面的代码不适用于“ArrayFormula” 例如:

"=ArrayFormula(GOOGLEMAPS_DISTANCE(a2:a,b2:b.,"driving"))"

不工作,我怎样才能将这个自定义函数转换为与“ArrayFormula”一起工作?

/**
 * Calculate the distance between two
 * locations on Google Maps.
 *
 * =GOOGLEMAPS_DISTANCE("NY 10005", "Hoboken NJ", "walking")
 *
 * @param {String} origin The address of starting point
 * @param {String} destination The address of destination
 * @param {String} mode The mode of travel (driving, walking, bicycling or transit)
 * @return {String} The distance in miles
 * @customFunction
 */
const GOOGLEMAPS_DISTANCE = (origin, destination, mode) => {
  const { routes: [data] = [] } = Maps.newDirectionFinder()
    .setOrigin(origin)
    .setDestination(destination)
    .setMode(mode)
    .getDirections();

  if (!data) {
    throw new Error('No route found!');
  }

  const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
  return distance;
};

我相信你的目标如下。

  • 您想将脚本与 ARRAYFORMULA 一起使用。

在这种情况下,使用 修改脚本怎么样?

修改后的脚本:

const GOOGLEMAPS_DISTANCE_ = (origin, destination, mode) => {
  const { routes: [data] = [] } = Maps.newDirectionFinder()
    .setOrigin(origin)
    .setDestination(destination)
    .setMode(mode)
    .getDirections();
  if (!data) {
    throw new Error('No route found!');
  }
  const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
  return distance;
};

const GOOGLEMAPS_DISTANCE = (origin, destination, mode) => {
  if (origin.map) {
    return origin.map((b, i) => GOOGLEMAPS_DISTANCE(b, destination[i], mode));
  } else if (origin && destination) {
    return GOOGLEMAPS_DISTANCE_(origin, destination, mode);
  }
  return null;
}
  • 使用此修改后的脚本时,请将=ARRAYFORMULA(GOOGLEMAPS_DISTANCE(A2:A,B2:B,"driving"))的函数放到一个单元格中。我认为在这个修改中,你可以同时使用=ARRAYFORMULA(GOOGLEMAPS_DISTANCE(A2:A,B2:B,"driving"))=GOOGLEMAPS_DISTANCE(A2:A,B2:B,"driving")
    • 在你的显示公式=ArrayFormula(GOOGLEMAPS_DISTANCE(a2:a,b2:b.,"driving"))中,我认为b2:b..需要去掉。请注意这一点。

参考: