Set Maps API key in Script Editor - google-maps

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 (e.g. 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;
}

Related

Google Apps Script - Contacts - Query on multiple strings

I'm working on a script to remove and re-add about 100 contacts. I have 12 different search criteria for ContactsApp.getContactsByEmailAddress, which the initiated know takes 30+ seconds to run. Is there some way I can only run it once and search all of my criteria? I've looked for others trying to do this same thing and was unsuccessful.
Below is one of the searches from my function (repeats 12 times with various search terms being passed to ContactsApp.getContactsByEmailAddress). I added the try-catch block because the script kept throwing errors out for seemingly no reason during various delete loops.
Would appreciate any and all advice.
var apa = ContactsApp.getContactsByEmailAddress('apa.')
try{
for (var i in apa) {
apa[i].deleteContact()
}
} catch(e){
Logger.log(e)
}
With the Contacts Service, you are limited to a single search criteria. Thus, the only way to search multiple patterns is to call the method once with each search parameter. You can, thankfully, use standard programming practices to minimize the amount of repeated code:
function getContactsWithEmails(emailSearchCriteria) {
if (!emailSearchCriteria || !emailSearchCriteria.length)
throw new Error("No search inputs given");
// Collect the results of each search into a single Array.
const matches = [];
emailSearchCriteria.forEach(function (email) {
var results = ContactsApp.getContactsByEmailAddress(email);
if (results.length)
Array.prototype.push.apply(matches, results);
else
console.log({message: "No results for search query '" + email + "'", query: email, resultsSoFar: matches});
});
return matches;
}
function deleteContacts(arrayOfContacts) {
if (!arrayOfContacts || !arrayOfContacts.length)
throw new Error("No contacts to delete");
arrayOfContacts.forEach(function (contact) {
ContactsApp.deleteContact(contact);
});
}
// Our function that uses the above helper methods to do what we want.
function doSomething() {
// Define all email searches to be performed.
const emailFragmentsToSearchWith = [
"email1",
...
"emailN"
];
const matchingContacts = getContactsWithEmails(emailFragmentsToSearchWith);
if (matchingContacts.length) {
/** do something with the contacts that matched the search.
* someMethodThatSavesContacts(matchingContacts);
* someMethodThatModifiesContacts(matchingContacts);
* deleteContacts(matchingContacts);
* ...
*/
}
/** do other stuff that doesn't need those contacts. */
}
The Google Calendar v3 GData API, as mentioned in this SO question, does support multiple query parameters. However, there is no simple integration with this API - you will need to write the appropriate URL requests and execute them with UrlFetchApp.
In addition to the Google Contacts API, you could use the Google People REST API, specifically the people.connections#list endpoint.
Both of these APIs require you to associate your Apps Script project with a Google Cloud Project that has the respective API enabled, and will likely require you to manually set the scopes your Apps Script project requires in its manifest file, in addition to providing OAuth2 authorizations of the associated HTTP requests you make to the API endpoints.
References
Accessing External APIs
Enabling Google APIs (steps 3-5)
Google Contacts API v3
Google People API
Array#forEach

Accessing Maps from Google Apps script bound to form

I’m trying to access Maps from a script bound to a Google form. The problem i’m having is that when debugging the script, it accesses Maps so often that i’m Running into quota limits. I have a Maps API key but do not have a client ID so can’t get Maps.setAuthenication(clientID,Key) to work. I’m doing this for a Scout Troop so don’t want to have to pay to access maps.
Can anyone help?
I was subsequently asked to post my code, and so here it is:
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);
}
One solution to limit the use of low-quota services is to avoid calling those services when the desired information has not changed.
For example, through the use of CacheService, you can dramatically reduce your calls to the Maps API, debugging session or not:
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 = ...
...
Your "gLocation" variable may be directly usable as a cache key. If not, you'll need to make it useable by encoding it. The max length key is 250 characters. This single-parameter caching assumes your directions all have a fixed endpoint, as shown in your example code. If both endpoints vary, you'll have to construct a cache key based on both values.
Related question: Maps direction Quota limits

How do I get Google search results from urlfetch in google apps script

I have been trying the following code
var response = UrlFetchApp.fetch("https://www.google.com/#q=this+is+a+test");
var contentText = response.getContentText();
Logger.log(contentText);
var thisdoc=DocumentApp.getActiveDocument().getBody() ;
thisdoc.setText(contentText);
Logger.log(contentText.indexOf("About"));
But it only seems to return the header, and empty body, and none of the search results. At minimum I should be able to see the "About xxx results" at the top of the browser but this doesn't appear in the text nor does the indexOf return a positive screen. I'm wondering if the search results are populated post page load meaning the body tag would indeed be empty and if so is there a workaround?
Edit: No it doesn't break the TOS as this is a GAFE app (which is a business app) and for business accounts they have both free and premium models of access to their API.
Google provides an API for authorized searches, so don't fuss with scraping web pages.
For example, you can use the Custom Search API with UrlFetch().
From the script editor, go to Resources -> Developer's Console Project... -> View Developer's Console. Create a new key for Public API access. Follow the instructions from the Custom Search API docs to create a Custom search engine. Enter the key and ID into the script where indicated. (More details below.)
This example script will return an object containing the results of a successful search; you can navigate the object to pull out whatever info you want.
/**
* Use Google's customsearch API to perform a search query.
* See https://developers.google.com/custom-search/json-api/v1/using_rest.
*
* #param {string} query Search query to perform, e.g. "test"
*
* returns {object} See response data structure at
* https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
*/
function searchFor( query ) {
// Base URL to access customsearch
var urlTemplate = "https://www.googleapis.com/customsearch/v1?key=%KEY%&cx=%CX%&q=%Q%";
// Script-specific credentials & search engine
var ApiKey = "--get from developer's console--";
var searchEngineID = "--get from developer's console--";
// Build custom url
var url = urlTemplate
.replace("%KEY%", encodeURIComponent(ApiKey))
.replace("%CX%", encodeURIComponent(searchEngineID))
.replace("%Q%", encodeURIComponent(query));
var params = {
muteHttpExceptions: true
};
// Perform search
Logger.log( UrlFetchApp.getRequest(url, params) ); // Log query to be sent
var response = UrlFetchApp.fetch(url, params);
var respCode = response.getResponseCode();
if (respCode !== 200) {
throw new Error ("Error " +respCode + " " + response.getContentText());
}
else {
// Successful search, log & return results
var result = JSON.parse(response.getContentText());
Logger.log( "Obtained %s search results in %s seconds.",
result.searchInformation.formattedTotalResults,
result.searchInformation.formattedSearchTime);
return result;
}
}
Example:
[15-05-04 18:26:35:958 EDT] {
"headers": {
"X-Forwarded-For": "216.191.234.70"
},
"useIntranet": false,
"followRedirects": true,
"payload": "",
"method": "get",
"contentType": "application/x-www-form-urlencoded",
"validateHttpsCertificates": true,
"url": "https://www.googleapis.com/customsearch/v1?key=--redacted--&cx=--redacted--&q=test"
}
[15-05-04 18:26:36:812 EDT] Obtained 132,000,000 search results in 0.74 seconds.
Identify your application to Google with API key
(excerpted from Google's documentation.)
Go to the Google Developers Console.
Select a project, or create a new one.
In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Custom Search API.
. . .
In the sidebar on the left, select Credentials.
Create your application's API key by clicking Create new Key under Public API access. For Google Script use, create a Browser key.
Once the Key for browser applications is created, copy the API key into your code.
Create a custom search engine
Follow the instructions here. Once you've created your custom search engine, copy the Search engine ID into your code.

How to authorize and post/update Trello card from a Google docs script

I have a Google Docs Spreadsheet that I'd like to use to update referenced cards in Trello. I've had some success with oauth and pulling data via their HTTP API, but am stuck with the following:
1) it seems Trello's code.js requires a window object, which the Google Doc script doesn't provide. So, I am stuck using their HTTP API.
2) authenticating via OAuth works, but only gives me read access. I cannot update cards with the token I am able to get.
function test() {
var oauthConfig = UrlFetchApp.addOAuthService("trello");
oauthConfig.setAccessTokenUrl("https://trello.com/1/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://trello.com/1/OAuthGetRequestToken");
oauthConfig.setAuthorizationUrl("https://trello.com/1/authorize?key=" + consumerKey + "&name=trello&expiration=never&response_type=token&scope=read,write");
//oauthConfig.setAuthorizationUrl("https://trello.com/1/OAuthAuthorizeToken"); <-- this only gives read access. Cannot POST
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);
var url = 'https://trello.com/1/cards/yOqEgvzb/actions/comments&text=Testing...';
var postOptions = {"method" : "post",
"oAuthServiceName": "trello",
"oAuthUseToken": "always"};
var response = UrlFetchApp.fetch(url, postOptions); // "Request failed for returned code 404. Truncated server response: Cannot POST"
Logger.log(response.getContentText());
}
I've found a number of related questions but no direct answers:
How to get a permanent user token for writes using the Trello API?
Trello API: vote on a card
Trello API: How to POST a Card from Google Apps Script (GAS)
Google apps script oauth connect doesn't work with trello
Many thanks ahead of time for any advice.
In order to get write access, you need to change the authorization url.
This example works for me
var oauthConfig = UrlFetchApp.addOAuthService("trello");
oauthConfig.setAccessTokenUrl("https://trello.com/1/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://trello.com/1/OAuthGetRequestToken");
oauthConfig.setAuthorizationUrl("https://trello.com/1/OAuthAuthorizeToken?scope=read,write");
on 1) yes you cant use the library from server gas, its meant to be run from a browser.
on 2), Ive done it from GAS with write access without problems. You need to use the format:
https://api.trello.com/1/.../xxxx?key=yyyyyy&token=zzzzzzz&...
and when you get the token, you need to request permanent access (no expiration) and write access, as in:
https://trello.com/1/authorize?key="+key+"&name=xxxxxxx&expiration=never&response_type=token&scope=read,write"
As in:
function postNewCardCommentWorker(cardId, comment, key, token) {
var commentEncoded=encodeURIComponent(comment);
var url = "https://api.trello.com/1/cards/"+cardId+"/actions/comments?text="+commentEncoded+"&key="+key+"&token="+token;
var options =
{
"method" : "POST"
};
UrlFetchApp.fetch(url, options);
}

Is it possible to impersonate domain's users with Google Drive API using Google Apps Script?

I am a head of studies and school administrator of our Google Apps for Education.
I used Google Apps Script for a lot of applications (control of absences, sending emails, automatic reporting, ScriptDb databases and more) using gas services. It's fantastic.
Basically I need to create a folder structure (years, courses, teachers, ...) within the Google Drive of students.
With Google Apps Script services I can do it easily but then the folders belong to the creator (administrator) and I think then users spend the administrator storage quota. This does not interest me.
(Yes, I can make an application to be executed by the users and create the structure in its Google Drive, but I'd rather do it in an automated manner and without intervention)
To create this documents (and folders) in Google Drive users (teachers, students, ...) have adapted the code provided by Waqar Ahmad in this response [ Add an writer to a spreadsheet ... ]
That allows me to take possession of documents of other users to make updates using the Google Document List API (Google Apps administrative access to impersonate a user of the domain) and also have adapted to create folders and files on other Google Drive users. It works perfectly. I mention here:
How to add a Google Drive folder ...
But now, the version 3 of the Google Documents List AP, has been officially deprecated and encourage us to work with the Google API Drive.
I tried to do the same with this new Google API. Has anyone managed to do this? Is it possible? I have no idea where to start!
Thank you.
Sergi
Updated:
This is the code i'm working but I get an "invalid request" error:
(...)
var user = e.parameter.TB_email // I get user from a TextBox
//https://developers.google.com/accounts/docs/OAuth2ServiceAccount
//{Base64url encoded header}.{Base64url encoded claim set}.{Base64url encoded signature}
//{Base64url encoded header}
var header = '{"alg":"RS256","typ":"JWT"}'
var header_b64e = Utilities.base64Encode(header)
//{Base64url encoded claim set}
var t_ara = Math.round((new Date().getTime())/1000) // now
var t_fins = t_ara + 3600 // t + 3600 sec
var claim_set = '{"iss":"1111111111-xxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com",'+
'"prn":"' + user + '",' +
'"scope":"https://www.googleapis.com/auth/prediction",'+
'"aud":"https://accounts.google.com/o/oauth2/token",'+
'"exp":'+t_fins+','+
'"iat":'+t_ara+'}'
// where '1111111111-xxxxxxxxxxx... is my CLIENT-ID (API Access -> Service Account)
var claim_set_b64e = Utilities.base64Encode(claim_set)
claim_set_b64e = claim_set_b64e.replace(/=/g,'')
var to_sign = header_b64e + '.' + claim_set_b64e
// [signature bytes] ??? // password 'isnotasecret???'
var key_secret = DocsList.getFileById('0Biiiiiiiiii-XXXXXXXXXXX').getBlob().getBytes()
// where '0Biiiiiiiiii-XXXXXXXXXXX'... is my p12 file (key_secret) uploaded to GDRive
// I don't know if this is correct !!!
var sign = Utilities.base64Encode(Utilities.computeHmacSha256Signature(to_sign, key_secret))
var JWT_signed = to_sign + '.' + sign
JWT_signed = JWT_signed.replace(/=/g,'')
// Token Request /////////////////////////////////////////////////////////////
var url = 'https://accounts.google.com/o/oauth2/token'
//var url = 'https%3A%2F%2Faccounts.google.com%2Fo%2Foauth2%2Ftoken' ???
//var url = 'https:' + '%2F%2Faccounts.google.com%2Fo%2Foauth2%2Ftoken' ???
var parameters = {
"method" : "POST",
"payload" : '"' + 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=' + JWT_signed + '"',
"contentType" : "application/x-www-form-urlencoded"
}
var content = UrlFetchApp.fetch(url,parameters) //.getContentText()
// Token Request end ////////////////////////////////////////////////////////
And I get an "Invalid Request" and not a JSON with the token
The 2 first parts ( header & claim set ) are OK. The result are equal to the result of Google OAuth page.
I don't know if the signature part are correct or if the error is in the token request.
The issue with your example above is that it it's computing the signature with hmacsha256. You need to use rsasha256. There are two service account libraries for apps script right now. One that I put together is:
https://gist.github.com/Spencer-Easton/f8dad65932bff4c9efc1
The issue with both libraries is they are derived from jsrsa which runs very slow on the server side.