我在 Google Apps Scripts 和 Google Sheets 中有一個自定義公式,可以給出兩個城市之間的距離。
筆記:
- 我發現一個單元格由于位置無效或找不到路線而回傳錯誤,因此我嘗試捕獲它。
- 如果一行在任一單元格上都沒有值,它將洗掉距離列。
uj5u.com熱心網友回復:
為了使這個函式陣列兼容,
檢查它是否是一個陣列并映射 它的元素
如果不是陣列,直接傳遞元素
快取服務也可用于避免重復呼叫地圖。
/**
* @param {string} origin
* @param {string} destination
*/
function MILEAGE_(origin, destination) {
try {
const sCache = CacheService.getScriptCache();
const key = `${origin}_${destination}`;
const cached = sCache.get(key);
if (cached) return Number(cached);
Utilities.sleep(1);
const directions = Maps.newDirectionFinder()
.setRegion('US')
.setOrigin(origin)
.setDestination(destination)
.getDirections();
const route = directions.routes[0].legs[0];
const distance = route.distance.value * 0.000621371;
sCache.put(key, String(distance), 21600);
return distance;
} catch {
return '#ERROR';
}
}
/**
* @param {A1:D1} arr
* @param {A1} param1
* @param {C1} param2
* @customfunction
*/
const mileage = (...arr) =>
Array.isArray(arr[0]) ? arr[0].map(e => MILEAGE_(...e)) : MILEAGE_(...arr);
用法:
=MILEAGE("origin","destination")
=MILEAGE(A1,B1)
=MILEAGE(A1:B100)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358821.html
