简体   繁体   English

在脚本编辑器中设置Maps API密钥

[英]Set Maps API key in Script Editor

As far as I understand, in order to track our quota usage, we need to provide our API key to the Google App Service on the service we are planning to use. 据我了解,为了跟踪我们的配额使用情况,我们需要在我们计划使用的服务上向Google App Service提供API密钥。

In my case I have a spreadsheet with Origin and Destination and a Custom function to calculate the distance between. 在我的例子中,我有一个带有Origin和Destination的电子表格以及一个自定义函数来计算它们之间的距离。

I ran into the problem of meeting the quota from invoking .getDirections() : 我遇到了通过调用.getDirections()来满足配额的问题:

Error: Service invoked too many times for one day: route. 错误:服务调用太多次一天:路由。 (line **). (行**)。

Sample of the code: 代码示例:

 function getDirections_(origin, destination) {
  var directionFinder = Maps.newDirectionFinder();
  directionFinder.setOrigin(origin);
  directionFinder.setDestination(destination);
  var directions = directionFinder.getDirections();  
  return directions;
}

So I read that if I assign the API Key to my project I should be able to see the usage and how close to the free quota I am. 所以我读到如果我将API密钥分配给我的项目,我应该能够看到使用情况以及我与免费配额的接近程度。

In the script editor, I did enable all of the APIs under Resources menu/ Advanced Google Services. 在脚本编辑器中,我确实启用了“资源”菜单/“高级Google服务”下的所有API。 Then I went to the Google Developers Console and there I did not see any record of how many times my custom function called the Google Maps API or any API usage. 然后我去了Google Developers Console,在那里我没有看到任何关于我的自定义函数调用Google Maps API或任何API使用次数的记录。

Logically I think that in my script I need to set my google API Key so my scripts start to call the API under my user name and count the number of time I used certain API. 从逻辑上讲,我认为在我的脚本中我需要设置我的谷歌API密钥,以便我的脚本开始以我的用户名调用API并计算我使用某些API的时间。 I guess right now I am using the Google Maps API as anonymous and since the whole company is assigned with the same IP, so we exhaust the permitted numbers to call this function. 我想我现在正在使用谷歌地图API作为匿名,因为整个公司被分配了相同的IP,所以我们用尽许多数字来调用这个功能。

Bottom line please reply if you know a way to connect my simple Spreadsheet function to the Public API access Key I have. 如果你知道一种方法将我的简单电子表格功能连接到我拥有的公共API访问密钥,请回复底线。

Thank you, Paul 谢谢你,保罗

I also have been eager to find this answer for a long time and am happy to say that I've found it. 我也渴望在很长一段时间内找到这个答案,我很高兴地说我找到了它。 It looks like Google might have just made this available around Oct 14, 2015 based on the date this page was updated. 看起来Google可能会在2015年10月14日左右根据此页面更新日期提供此功能

You can leverage the UrlFetchApp to add your API key. 您可以利用UrlFetchApp添加API密钥。 The link I posted above should help with obtaining that key. 我上面发布的链接应该有助于获取该密钥。

function directionsAPI(origin, destination) {
 var Your_API_KEY = "Put Your API Key Here";
 var serviceUrl = "https://maps.googleapis.com/maps/api/directions/json?origin="+origin+"&destination="+destination+
"&mode="+Maps.DirectionFinder.Mode.DRIVING+"&alternatives="+Boolean(1)+"&key="+Your_API_KEY;

 var options={
  muteHttpExceptions:true,
  contentType: "application/json",
 };

 var response=UrlFetchApp.fetch(serviceUrl, options);
  if(response.getResponseCode() == 200) {
   var directions = JSON.parse(response.getContentText());
    if (directions !== null){
     return directions;
     }
    }
  return false;
 }

So walking through the code... first put in your API key. 因此,遍历代码......首先输入您的API密钥。 Then choose your parameters in the var serviceUrl. 然后在var serviceUrl中选择您的参数。 I've thrown in additional parameters (mode and alternatives) to show how you can add them. 我已经抛出了额外的参数(模式和替代方案)来展示如何添加它们。 If you don't want them, remove them. 如果您不想要它们,请将它们删除。

With UrlFetch you can add options. 使用UrlFetch,您可以添加选项。 I've used muteHttpExceptions so that the fetch will not throw an exception if the response code indicates failure. 我已经使用了muteHttpExceptions,因此如果响应代码指示失败,则fetch不会抛出异常。 That way we can choose a return type for the function instead of it throwing an exception. 这样我们可以为函数选择一个返回类型,而不是抛出异常。 I'm using JSON for the content type so we can use the same format to send and retrieve the request. 我正在使用JSON作为内容类型,因此我们可以使用相同的格式来发送和检索请求。 A response code of 200 means success, so directions will then parse and act like the object that getDirections() would return. 响应代码200表示成功,因此方向将解析并像getDirections()将返回的对象一样行动。 The function will return false if the UrlFetch was not successful (a different response code) or if the object is null. 如果UrlFetch不成功(不同的响应代码)或者对象为null,则该函数将返回false。

You will be able to see the queries in real time in your developer console when you look in the Google Maps Directions API. 当您查看Google Maps Directions API时,您将能够在开发者控制台中实时查看查询。 Be sure that billing is enabled, and you will be charged once you exceed the quotas. 确保已启用结算,超出配额后将向您收取费用。

1.) I added an API key from my console dashboard. 1.)我从控制台仪表板添加了一个API密钥。 Remember to select the correct project you are working on. 请记住选择正在处理的正确项目。 https://console.developers.google.com/apis/credentials?project= https://console.developers.google.com/apis/credentials?project=

2.) In my Project (Scripts Editor) I setAuthentication to Maps using the API key and the Client ID from the console. 2.)在我的项目(脚本编辑器)中,我使用API​​密钥和控制台中的客户端ID将身份验证设置为映射。 I have included the script below: 我已经包含以下脚本:

function getDrivingDirections(startLoc, wayPoint, endLoc){
   var key = "Your_API_Key";
   var clientID = "Your_Client_ID";
   Maps.setAuthentication(clientID, key);
   var directions =  Maps.newDirectionFinder()
        .setOrigin(startLoc)
        .addWaypoint(wayPoint)
        .setDestination(endLoc)
        .setMode(Maps.DirectionFinder.Mode.DRIVING)
        .getDirections();
} return directions;

https://developers.google.com/apps-script/reference/maps/maps#setAuthentication(String,String) https://developers.google.com/apps-script/reference/maps/maps#setAuthentication(String,String)

As of 7/13/2017, I was able to get the API to function by enabling the Sheets API in both the "Advanced Google Services" menu (images 1 and 2), and in the Google Developer Console. 自2017年7月13日起,我可以通过在“高级Google服务”菜单(图片1和2)以及Google Developer Console中启用Sheets API来启用API。 If you're logged into Google Sheets with the same email address, no fetch function should be necessary. 如果您使用相同的电子邮件地址登录Google表格,则无需提取功能。

[In the Resources menu, select Advanced Google Services.][1] [在“资源”菜单中,选择“高级Google服务”。] [1]

[In Advanced Google Services, make sure the Google Sheets API is turned on.][2] [在高级Google服务中,请确保已打开Goog​​le表格API。] [2]

[1]: [1]: [2]: [2]:

Thank goodness for JP Carlin! 谢天谢地,JP Carlin! Thank you for your answer above. 谢谢你的回答。 JP's answer also explains his code. JP的回答也解释了他的代码。 Just to share, without a code explanation (just go look above for JP Carlin's explanation), below is my version. 只是为了分享,没有代码解释(只需看看上面的JP Carlin的解释),下面是我的版本。 You will see that I also have the departure_time parameter so that I will get distance and driving-minutes for a specific date-time. 您将看到我还有departure_time参数,以便我可以获得特定日期时间的距离和驾驶分钟数。 I also added a call to Log errors (to view under "View/Logs"): 我还添加了对Log错误的调用(在“View / Logs”下查看):

Note: Google support told me that using your API-key for Google Maps (eg with "Directions API") with Google Sheets is not supported. 注意:Google支持人员告诉我, 支持在Google地图中使用Google地图的API密钥(例如使用“Directions API”)。 The code below works, but is an unsupported work-around. 下面的代码有效,但是不受支持的解决方法。 As of 11/4/2018, Google has an internal ticket request to add support for Google Maps APIs within Google Sheets, but no timeline for adding that feature. 截至11/4/2018,Google有一个内部故障单请求,要求在Google表格中添加对Google Maps API的支持,但没有添加该功能的时间表。

/********************************************************************************
 * directionsAPI: get distance and time taking traffic into account, from Google Maps API
********************************************************************************/
function directionsAPI(origin, destination, customDate) {
        var Your_API_KEY = "<put your APK key here between the quotes>";
        var serviceUrl = "https://maps.googleapis.com/maps/api/directions/json?origin="+origin+"&destination="+destination+"&departure_time="+customDate.getTime()+"&mode="+Maps.DirectionFinder.Mode.DRIVING+"&key="+Your_API_KEY;

        var options={
          muteHttpExceptions:true,
          contentType: "application/json",
         };

        var response=UrlFetchApp.fetch(serviceUrl, options);
          if(response.getResponseCode() == 200) {
           var directions = JSON.parse(response.getContentText());
            if (directions !== null){
             return directions;
             }
            }
      Logger.log("Error: " + response.getResponseCode() + " From: " + origin + ", To: " + destination + ", customDate: " + customDate + ", customDate.getTime(): " + customDate.getTime() );
      return false;
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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