簡體   English   中英

提供API密鑰,以避免來自Apps腳本中Maps Service的命中限制錯誤

[英]Supply API key to avoid Hit Limit error from Maps Service in Apps Script

我有一個Google表格,可以通過Maps Service獲取兩個緯度/經度之間的行駛距離。 下面的函數有效,但是矩陣是4,500個單元格,因此出現“命中限制”錯誤。

如何在此處提供我的付費帳戶的API密鑰?

自定義功能

function drivingMeters(origin, destination) {
  if (origin=='' || destination==''){return ''}
  var directions = Maps.newDirectionFinder()
  .setOrigin(origin)
  .setDestination(destination)
  .getDirections();
  return directions.routes[0].legs[0].distance.value ;
}

使用示例:

A1: =drivingMeters($E10,G$9)

Where E10 = 42.771328,-91.902281
  and G9  = 42.490390,-91.1626620

根據文檔,您應在調用其他方法之前使用身份驗證詳細信息初始化Maps服務

您的客戶ID和簽名密鑰可以從Google Enterprise支持門戶獲取。 將這些值設置為null可返回使用默認配額限額。

我建議將這些值存儲在PropertiesService並使用CacheService來提供快速訪問。 使用這種方法,而不是在腳本項目的主體中編寫它們,意味着如果您的腳本以庫的形式發布,它們將不會被其他編輯器無意復制,推送到共享代碼存儲庫或其他開發人員可見。

此外,我建議重寫自定義函數以接受數組輸入並返回適當的數組輸出-這將有助於加快其執行速度。 Google在自定義功能頁面上提供了一個示例: https : //developers.google.com/apps-script/guides/sheets/functions#optimization

使用道具/緩存的示例: 道具實例

function authenticateMaps_() {
  // Try to get values from cache:
  const cache = CacheService.getScriptCache();
  var props = cache.getAll(['mapsClientId', 'mapsSigningKey']);
  // If it wasn't there, read it from PropertiesService.
  if (!props || !props.mapsClientId || !props.mapsSigningKey) {
    const allProps = PropertiesService.getScriptProperties().getProperties();
    props = {
      'mapsClientId': allProps.mapsClientId,
      'mapsSigningKey': allProps.mapsSigningKey
    };
    // Cache these values for faster access (max 6hrs)
    cache.putAll(props, 21600);
  }
  // Apply these keys to the Maps Service. If they don't exist, this is the
  // same as being a default user (i.e. no paid quota).
  Maps.setAuthentication(props.mapsClientId, props.mapsSigningKey);
}
function deauthMaps_() {
  Maps.setAuthentication(null, null);
}

// Your called custom function. First tries without authentication,
// and then if an error occurs, assumes it was a quota limit error
// and retries. Other errors do exist (like no directions, etc)...
function DRIVINGMETERS(origin, dest) {
  if (!origin || !destination)
    return;
  try {
    return drivingMeters_(origin, dest);
  } catch (e) {
    console.error({
      message: "Error when computing directions: " + e.message,
      error: e
    });
    // One of the possible errors is a quota limit, so authenticate and retry:
    // (Business code should handle other errors instead of simply assuming this :) )
    authenticateMaps_();
    var result = drivingMeters_(origin, dest);
    deauthMaps_();
    return result;
  }
}

// Your implementation function.
function drivingMeters_(origin, dest) {
  var directions = Maps.newDirectionFinder()
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM