简体   繁体   中英

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.

In my case I have a spreadsheet with Origin and Destination and a Custom function to calculate the distance between.

I ran into the problem of meeting the quota from invoking .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.

In the script editor, I did enable all of the APIs under Resources menu/ Advanced Google Services. 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.

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. 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.

Bottom line please reply if you know a way to connect my simple Spreadsheet function to the Public API access Key I have.

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.

You can leverage the UrlFetchApp to add your API key. 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. Then choose your parameters in the 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. I've used muteHttpExceptions so that the fetch will not throw an exception if the response code indicates failure. 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. A response code of 200 means success, so directions will then parse and act like the object that getDirections() would return. The function will return false if the UrlFetch was not successful (a different response code) or if the object is null.

You will be able to see the queries in real time in your developer console when you look in the 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. Remember to select the correct project you are working on. 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. 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)

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. If you're logged into Google Sheets with the same email address, no fetch function should be necessary.

[In the Resources menu, select Advanced Google Services.][1]

[In Advanced Google Services, make sure the Google Sheets API is turned on.][2]

[1]: [2]:

Thank goodness for JP Carlin! Thank you for your answer above. JP's answer also explains his code. Just to share, without a code explanation (just go look above for JP Carlin's explanation), below is my version. 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. I also added a call to Log errors (to view under "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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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