繁体   English   中英

Apps 脚本中的 Google Maps API 不断失败

[英]Google Maps API In Apps Script Keeps Failing

我正在使用谷歌应用程序脚本为谷歌地图编写测距仪。 我找到了这样的例子,但它们一直失败,所以我想我会自己编写代码。 可悲的是,这失败了,并出现了同样的错误:

TypeError: Cannot read property "legs" from undefined. (line 16).

似乎它有时有效,有时无效。 我的工作表中有几 (3) 个地方正在调用相同的函数,有时一个或多个将返回有效响应。

我在其他地方看到人们建议使用 API 密钥来确保您得到良好的响应,所以这就是我在下面实现的。 (api 键已编辑!有没有什么好方法可以判断它们是否已被识别?)

任何想法可能会出错?!

提前致谢,

麦克风

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;
}

这是我在解决问题时的短期解决方案。

不理想,但至少尽可能减少使用您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM