【发布时间】:2021-04-08 08:06:22
【问题描述】:
我正在尝试升级下面的代码,使其能够接受数组输入。
const md5 = (key = '') => {
const code = key.toLowerCase().replace(/\s/g, '');
return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, key)
.map((char) => (char + 256).toString(16).slice(-2))
.join('');
};
const getCache = (key) => {
return CacheService.getDocumentCache().get(md5(key));
};
// Store the results for 6 hours
const setCache = (key, value) => {
const expirationInSeconds = 6 * 60 * 60;
CacheService.getDocumentCache().put(md5(key), value, expirationInSeconds);
};
const GOOGLEMAPS_DISTANCE = (origin, destination, mode = 'driving') => {
const key = ['distance', origin, destination, mode].join(',');
// Is result in the internal cache?
const value = getCache(key);
// If yes, serve the cached result
if (value !== null) return value;
const { routes: [data] = [] } = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.setMode(mode)
.getDirections();
if (!data) {
GOOGLEMAPS_DISTANCE;
}
const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
// Store the result in internal cache for future
setCache(key, distance);
return distance;
};
目前,代码能够找到两个给定地址之间的距离,并将其返回给单个输入。为了解决 Google 的 API 请求限制,我添加了缓存以前值的功能。此外,只要遇到错误(例如 API 请求限制),代码就会重新运行。
现在,我想升级函数以便能够接受origin 和destination 的数组。我找到了Google documentation 用于通过使用map 调用添加此功能,但我似乎无法使其工作。如果有人愿意回复并帮助我,我将不胜感激。
【问题讨论】:
标签: google-maps google-apps-script google-sheets google-api