【问题标题】:Accessing Maps from Google Apps script bound to form从绑定到表单的 Google Apps 脚本访问地图
【发布时间】:2018-08-28 14:21:41
【问题描述】:

我正在尝试从绑定到 Google 表单的脚本访问地图。我遇到的问题是,在调试脚本时,它经常访问地图,以至于我遇到了配额限制。我有一个 Maps API 密钥,但没有客户端 ID,因此无法让 Maps.setAuthenication(clientID,Key) 工作。我这样做是为了侦察部队,所以不想付费访问地图。

谁能帮忙?

随后我被要求发布我的代码,所以这里是:

 function setLocation(){
     var whereString;
     var theDuration;
     var theDistance;
     var theRoute;
     var theDirections;
     var theTravelString; 

     // this Sets the Where: Tab on the form
     whereString = 'Where: ' + gLocation;
     theItemArray = gSignupForm.getItems();
     theItemArray[kWhereItem].setTitle(whereString);
     //this gets the directions to the location
     Maps.setAuthentication('','ABCDEFGHIJKLMNOP'); 
     //Obviously Im'm not going to post the true key
     theDirections = Maps.newDirectionFinder()
         .setOrigin('7101 Shadeland Ave, Indianapolis, IN 46256')
         .setDestination(gLocation)
        .setMode(Maps.DirectionFinder.Mode.DRIVING)
        .getDirections();
     theRoute = theDirections.routes[0];
     theDuration = theRoute.legs[0].duration.text;
     theDistance = theRoute.legs[0].distance.text;
     theTravelString = Utilities.formatString('Travel Considerations: The estimated travel distance is %u miles. ',theDistance);
     theTravelString += 'The estimated travel time is ' + theDuration;
     theItemArray[kTravelItem].setTitle(theTravelString);
}

【问题讨论】:

  • 请分享您的代码并解释您想要实现的目标以及预期的结果。另外,请阅读“如何提问”stackoverflow.com/help/how-to-ask
  • 考虑使用 CacheService 以避免重复重新查询相同的信息。 IE。从给定的起点-终点对生成数据后,将其存储在缓存中长达 6 小时。然后在此处修改给定的位,以便在查询 Maps 之前先检查缓存。
  • 根据 doc,除非您拥有 Maps API for Business 帐户,否则您将无法使用 setAuthentication

标签: google-apps-script maps


【解决方案1】:

限制使用低配额服务的一种解决方案是避免在所需信息未更改时调用这些服务。

例如,通过使用CacheService,您可以显着减少对 Maps API 的调用,无论是否调试会话:

var cache = CacheService.getScriptCache();
function setLocation() {
  // Try to find the route for this location if it's still available
  var storedRoute = cache.get(gLocation);
  if (!storedRoute) {
    // No route for this value of the key gLocation was found. Query as normal.
    ...
    theRoute = theDirections.route[0];
    // Cache this route for future uses, for the maximum of 6hr).
    cache.put(gLocation, JSON.stringify(theRoute), 21600);
  } else {
    // We have this exact stored route! Convert it from the stored string.
    theRoute = JSON.parse(storedRoute);
  }
  theDuration = ...
  ...

您的“gLocation”变量可以直接用作缓存键。如果没有,您需要通过对其进行编码使其可用。最大长度密钥为 250 个字符。此单参数缓存假定您的方向都有一个固定的端点,如您的示例代码中所示。如果两个端点不同,则必须基于这两个值构造一个缓存键。

相关问题:Maps direction Quota limits

【讨论】:

  • 感谢您的建议。会试试的。
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多