[英]Google Maps API In Apps Script Keeps Failing
I'm using google apps script to code a distance finder for Google Maps.我正在使用谷歌应用程序脚本为谷歌地图编写测距仪。 I've found examples of such, but they keep failing, so I thought I'd code my own.
我找到了这样的例子,但它们一直失败,所以我想我会自己编写代码。 Sadly, this is failing with the same error:
可悲的是,这失败了,并出现了同样的错误:
TypeError: Cannot read property "legs" from undefined. (line 16).
It seems to be that it's sometimes working, and sometimes not.似乎它有时有效,有时无效。 I have a few (3) places in my sheet that are calling the same functions, and at times one or more will return a valid response.
我的工作表中有几 (3) 个地方正在调用相同的函数,有时一个或多个将返回有效响应。
I saw elsewhere that people were suggesting using an API key to make sure that you get a good response, so that's what I've implemented below.我在其他地方看到人们建议使用 API 密钥来确保您得到良好的响应,所以这就是我在下面实现的。 (api keys redacted! is there a good way to tell if they've been recognised?)
(api 键已编辑!有没有什么好方法可以判断它们是否已被识别?)
Any ideas what might be going awry?!任何想法可能会出错?!
Thanks in advance,提前致谢,
Mike麦克风
function mikeDistance(start, end){
start = "CV4 8DJ";
end = "cv4 9FE";
var maps = Maps;
maps.setAuthentication("#####", "#####");
var dirFind = maps.newDirectionFinder();
dirFind.setOrigin(start);
dirFind.setDestination(end);
var directions = dirFind.getDirections();
var rawDistance = directions["routes"][0]["legs"][0]["distance"]["value"];
var distance = rawDistance/1609.34;
return distance;
}
Here's my short term solution while the issue is being fixed.这是我在解决问题时的短期解决方案。
Not ideal, but at least reduces using your API limit as much as possible.不理想,但至少尽可能减少使用您的 API 限制。
function getDistance(start, end) {
return hackyHack(start, end, 0);
}
function hackyHack(start, end, level) {
if (level > 5) {
return "Error :(";
}
var directions = Maps.newDirectionFinder()
.setOrigin(start)
.setDestination(end)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();
var route = directions.routes[0];
if (!route) return hackyHack(start, end, level+1); // Hacky McHackHack
var distance = route.legs[0].distance.text;
// var time = route.legs[0].duration.text;
return distance;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.