How to add my key to this google app script? - google-apps-script

I need to update this script to pass my key so that I don't go over the limit per day. How would I modify this script to pass my key?
(NOTE: google class information found here: https://developers.google.com/apps-script/reference/maps/geocoder)
function geo2zip(a) {
var response=Maps.newGeocoder()
.reverseGeocode(lat(a),long(a));
return response.results[0].formatted_address.split(',')[2].trim().split(' ')[1];
}
function lat(pointa) {
var response = Maps.newGeocoder()
.geocode(pointa);
return response.results[0].geometry.location.lat
}
function long(pointa) {
var response = Maps.newGeocoder()
.geocode(pointa);
return response.results[0].geometry.location.lng
}
I have never used a google apps script before.
I have this script in place and am using "=geo2zip(cell)" to call the script from my google sheet to get the zip code for incomplete addresses. There are ~28k in my sheet. I have enabled the geocoding api in my google console and my billing info. and created my key but am not sure how to include my key in the script above.
I have also tried using the following to call the api using my key. It is working, but this has resulted in VERY slow responses. At the rate it is taking these to respond, it will take me 10 days to finish updating my 28k records.
CELL M4852--> "https://maps.googleapis.com/maps/api/geocode/xml?address=ADDRESS&key=MYKEY"
NEXT CELL--> "=ImportXML(M4852,"/GeocodeResponse/result/formatted_address")"
The script responds much more quickly, so I would prefer to use that and pass my key. Please let me know if you can help.
UPDATE: I was able to resolve this using Alberto's suggestion below of adding the Maps.setAuthentication.

I believe your issue has more to do with the Google API management than with the scripts themselves. There is a way to limit how much your key is used. According to the Maps Platform documentation:
Manage Your Cost of Use
To manage your cost of use of the Google Maps
Platform APIs, you can set daily limits to all requests to any
billable API.
To view or change daily billable limits for the Geocoding API, do the
following:
Go to the Geocoding API Quotas page in the Google Cloud Platform
Console. From the projects list, select a project. In the Requests
section, on the Requests per day line, click the edit icon, then enter
the preferred total billable daily quota, up to the limit (if any)
specified by Google.
You can basically set how many requests you want to allow per day, which will avoid you going over your limit.
UPDATE
You can link the script to your account using the Maps.setAuthentication(clientId, signingKey) method, according to the docs, it:
Enables the use of an externally established Maps API for Business
account, to leverage additional quota allowances. Your client ID and
signing key can be obtained from the Google Enterprise Support Portal.
Set these values to null to go back to using the default quota
allowances.
Map Documentation Link: https://developers.google.com/apps-script/reference/maps/maps#setAuthentication(String,String)
Quotas URL: https://console.cloud.google.com/project/_/apiui/apiview/geocoding_backend/quotas?_ga=2.141719605.643331044.1560431279-1498828710.1560431279
Documentation URL: https://developers.google.com/maps/documentation/geocoding/usage-and-billing

Related

Youtube Quota on new Project

I am using the Youtube API with Apps Script for the first time but I get a quota error. I activated the Youtube API from the Apps Script window, and added my scripts.
Note I am using a Google Workspace account. I didn't have this problem with my private google account.
Here is the code that generates the error:
function getVids() {
var list = YouTube.Search.list('id,snippet', {
channelId: 'UCYf_kU_HoMOUUe3hW-0ou5Q',
maxResults: 25
})
var json = JSON.parse(list);
var items = list.items;
var allVideos = [];
for (var i=1; i<items.length;i++) {
var videoId = list.items[i].id.videoId;
allVideos.push(videoId);
}
console.log(allVideos)
}
I receive this error:
GoogleJsonResponseException: API call to youtube.videos.insert failed
with error: The request cannot be completed because you have exceeded
your quota.
I tried looking at the consumption here: https://console.developers.google.com/apis/dashboard but it redirects me to https://console.developers.google.com/apis/dashboard?project=northern-math-286006&folder=&organizationId= which I assume is some default project name as I didn't choose it. I selected https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?folder=&organizationId=&project=northern-math-286006 from this page to view Youtube data but it returns "No data is available for the selected time frame."
Explanation:
According to the official documentation you have exceeded 10,000 units per day.
Unit points might be a little tricky to understand but there is a very good explanation on the link above itself:
You are doing SEARCH requests and for every search request you spend 100 units. I assume you have executed this code and/or other codes that consume points and this is why you reached your maximum unit points.
According to the documentation here you can see your quota usage but you might need to have permission to access that info.
YouTube Data API (v3) - Quota Calculator:
If your application calls a method, such as search.list, that returns
multiple pages of results, each request to retrieve an additional page
of results incurs the estimated quota cost.
Did you check your quota for this API? You can find your quotas under 'IAM &A Admin' -> Quotas. Then look for 'YouTube Data API V3'.
Click on the one saying 'Queries per day' and see if the Limit is set to 0.
If yes, you might try to disable this API and enable again.
I had this issue too, and after disabling and enabling the API I get the 10k units.

How many service calls am I allowed in a day?

I've set up two sets of address. One across the second row starting at B2 and another down the first column starting at A3. Using a custom function invoking google's api I am trying to get a list of drive times in minutes for all locations in the first column to all locations in the second row. I get an error stating that it has ran to many times in one day. Here is the custom function
function DriveTime(origin, destination) {
var directions = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.getDirections();
return directions.routes[0].legs[0].duration.value/60;
}
Error: Service invoked too many times in one day: route (line 2)
I understand the error, but how many times in one day can I make this call as a standard free user. And where can I find pricing to increase the amount of daily calls to this service?
Also if anyone knows of a way to accomplish this in less calls than I am attempting, that'd be welcomed knowledge as well.
Technically, your quota as a apps script user without API key/Billing information should be zero. But for whatever reason, Google didn't make changes to charge apps script Maps library when they changed the pricing back in June'18 for everything else related to Maps API. There seems to be a default quota, which is not explicitly mentioned in apps script documentation pages.
If you have had premium plan in the past, you can leverage Maps.setAuthentication(). But if you do not,
This method doesn't work with API keys. Additionally, please note that Premium Plan is no longer available for new customers. If you don't already have a Premium Plan license, please don't call setAuthentication(clientId, signingKey). You are able to use the Maps methods with the default quota allowances.
Which means you cannot extend the default quota allowance.
Your alternative would then be to call the maps api directlyskip oauth using urlfetchapp and parse the response using apps script vanilla javascript(es5).
You can see the pricing here.

How do I check if my domain is grandfathered?

I have thoroughly read through the updated google API Terms and Conditions:
https://developers.google.com/maps/pricing-and-plans/standard-plan-2016-update
Specifically, this excerpt:
Active domains created before June 22, 2016, continue to be able to access the Google Maps JavaScript API, Static Maps API, and Street View Image API without an API key. They are not affected by keyless access being unavailable for new domains.
My question is, how do I figure out if my domain is grandfathered and can continue to call the static maps API without the API_KEY parameter?
You can test if your domain was whitelisted by trying to load a map without an API key. If you manage to get the static map image it means you were whitelisted.
The whitelist has 25000 queries per day limit which is equivalent to the free quota limit when you are using a key.
To be able to monitor your usage and, if needed, get more quota it would be best for you to start using an API key. You can then check quota and monitor your usage in the Google Developer Console

Access Denied when attempting to use Google Maps Geocoding Service with a Console API Key

UPDATE: In an effort to give a more clear question. How do I use the Google Console API key with the Google Maps Geocoding Web Service API? At the moment the request comes back as denied, when I specify the key but even though it failed it is logged in the Google Console API site's reports section.
Original Question
I have an existing app that has been modified to start geocoding address at the time they are entered (for use within the app on a Google Map). The volume expected for this is expcted to be within the free offering's limites and does not require a key at this time. However now I have to geocode all of the existing addresses. I have a small windows app (C#) that will loop through them one at a time, request they be geocoded (via https://maps.googleapis.com/maps/api/geocode/json) and store the results in the database. However I keep running into the query limit. To help alleviate this I've setup an account on Google API Console (https://code.google.com/apis/console/) so that I get go over the limit and just be billed for the overages.
The problem is in order to do utilize this billing alternative I have to provide a Console API Key to the request, but every time I do so I get a response back with a status of REQUEST_DENIED.
My URL looks like this
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA+94043&sensor=false&key=123abc
If I take off the key it works fine, but with it on it fails. Now, I have seen other questions similar to this when looking around but can find no answer to the issue.
I've tried various alternate domains including maps.google.com, maps.googleapis.com and maps-api-ssl.google.com all seem to have the same problem from what I can tell.
Here's what I've been able to find out so far:
The service is listed in the Google Console API's site as Google Maps API v3, (there is a separate entry for v2) so I don't think it's a problem with keys no longer being mandatory in v3.
I know the requests are getting through and being correctly logged against this API key because with each failed attempt the request count goes up by one on the Reports tab of the Google APIs Console.
*I know it's not a problem with it not being accessed via a web page because the Console API explicitly lets you generates keys intended for Server/Service use and you can restrict access to them via IP address, not URL Referrer.
*I've also verified the parameter syntax as it's outlined on this page, as are other usage
*These seem to be generic to the Console API system but there is no mention of exceptions to these practices when used for the Google Maps API.
I even tried to contact Google but apparently they don't offer support over the phone (I was hoping to be done with this today but that's not looking likely).
It seems the key is not necessary anymore, since it doesn't increase your limit of free geocodings.
It was a legacy of v2, but geocoding API v2 was fully deprecated last March, 8.
If you need to use more than the free limit, I think you must adquire the Enterprise license.
Regards,
Eduardo.
I ran into this same issue and solved it by enabling the Geocoding API on the Google apis dashboard. Even though I'm using the Google Maps JavaScript API v3, it still required me to enable the Geocoding API as well. Make sure you understand the google's quota limits and billing system before enabling any API access. Hope this helps!
Late to this answer, but just in case anyone else has issue. Billing needs to be setup first and like Dylan said you also have to enable Geocoding API(this got me). At least I did for my locations app that shows multiple store location addresses.

Google Maps API Key - Get one for everyone of my users programmatically?

I saw that one has not to obtain a Google Maps API key if you want to use their maps api in general, only if you want to use their web services and statistics etc.
Now I have two questions regarding this:
If I have a public website which uses the Google Maps API to display a map with default options. How does Google count the API calls if I don't use an API key? (Maybe with the help of the domain which requests the map?)
If they do so and my site exceeds the 25k calls/day, is there a possiblity that my users can login with their Google account on my site and some backend logic will get them an API key from Google that I store e.g. in a database. So I could use the API keys of my users to bypass the API usage limits only for my site.
Assuming you are using the Javascript API v3:
This SO question partially answers your queries.
Have a look at the usage limits, it looks like that you cannot use more than one API key:
Can I use more than one API key to increase my available usage over
the documented limits?
Google reserves the right to withhold access to the Maps API from any site that attempts to use more than the permitted number of map
loads of the Maps API without permission, and fails to respond when
contacted by Google.
Though this may be debatable, to me it seems a bad idea using your user's API key. For sure you need to ask the permission, then you have to monitor their quotas and so on, a minefield...
TL;DR if you exceed constantly the daily quota you should purchase a larger quota.