Google Maps API without key? - javascript

How do you utilize Google Maps v3 API without the key? I've seen it in this example but cannot figure out what specifically is causing it not to error out.
Edit: In case someone suggests it, the other answers on this topic on StackOverflow are outdated and no longer applicable.

A key is now required. Previously it wasn't required and sites that used the API without a key prior to June 22, 2016 have been grandfathered to allow them to continue to work.
See this blog post for additional information (relevant text below):
As of June 22, 2016 we are making the following changes to the Google Maps APIs Standard Plan:
We no longer support keyless access (any request that doesn't include an API key). Future product updates are only available for requests made with an API key. API keys allow us to contact developers when required and help us identify misbehaving implementations.
We have implemented a simple 25,000 map loads per day free limit to new Google Maps JavaScript API, Static Maps API, and Street View Image API implementations. The confusing 90-consecutive-day grace period for these APIs is being retired on October 12, 2016. With this change, developers can predictably plan for growth while media sites and US nonprofits can request more quota at no charge via our dedicated support programs.
We have reduced the daily map load maximum limit you can purchase for Google Maps JavaScript API, Static Maps API, and Street View Image API from 1,000,000 to 100,000 requests per API.* We believe higher-volume developers are best served with a Premium Plan license, which includes technical support and a Service Level Agreement, and with this change we've also created consistency between Standard Plan quotas across our maps and web service APIs.
We now count Google Maps JavaScript API client-side requests towards the daily limit of the associated web service API.*
The new policies will apply immediately to all Maps API implementations created on or after June 22nd, 2016.
Existing applications have been grandfathered based on their current usage to ensure that they continue to function both now and in the future. We will also be proactively contacting all existing API key users who, based on usage growth patterns, may be impacted in the future. If you’re an existing user, please take the time to read our Policy Update for Standard Plan summary for details on how each of these changes might affect your implementation.

Indeed the link you posted http://www.birdtheme.org/useful/v3largemap.html works without key (there is just a warning in the console).
It looks like Google is whitelisting some domain names to allow the use of API without key.
I tried to use the Google Maps API v3 to display OpenStreetMap tiles but it produces a "Google Maps API error: MissingKeyMapError" on my localhost while it is working on this site without API key: http://harrywood.co.uk/maps/examples/google-maps/apiv3.html
On most websites that don't use an API key, there is an error that prevent the use of Google Maps but you can bypass this censorship.
Solution if you don't own the server using Google Maps API without key:
Block the HTTP request sending the error with an addon like AdBlockPlus and the rule http://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate?*
This will give you access to Google Maps API tiles, markers, infoWindow popup...
But if you want to use the Geocoding API, you also have to remove your HTTP referer header with a browser addon like "Modify Headers".
Solution to add in your web page so every visitors can access Google Maps API without key:
Below is a JavaScript hack I created to use Google Maps API V3 without key and bypass the error message.
// hack Google Maps to bypass API v3 key (needed since 22 June 2016 http://googlegeodevelopers.blogspot.com.es/2016/06/building-for-scale-updates-to-google.html)
var target = document.head;
var observer = new MutationObserver(function(mutations) {
for (var i = 0; mutations[i]; ++i) { // notify when script to hack is added in HTML head
if (mutations[i].addedNodes[0].nodeName == "SCRIPT" && mutations[i].addedNodes[0].src.match(/\/AuthenticationService.Authenticate?/g)) {
var str = mutations[i].addedNodes[0].src.match(/[?&]callback=.*[&$]/g);
if (str) {
if (str[0][str[0].length - 1] == '&') {
str = str[0].substring(10, str[0].length - 1);
} else {
str = str[0].substring(10);
}
var split = str.split(".");
var object = split[0];
var method = split[1];
window[object][method] = null; // remove censorship message function _xdc_._jmzdv6 (AJAX callback name "_jmzdv6" differs depending on URL)
//window[object] = {}; // when we removed the complete object _xdc_, Google Maps tiles did not load when we moved the map with the mouse (no problem with OpenStreetMap)
}
observer.disconnect();
}
}
});
var config = { attributes: true, childList: true, characterData: true }
observer.observe(target, config);
This will give you access to Google Maps API tiles, markers, infoWindow popup...
For the Geocoding API, you also have to remove your HTTP referer with the HTML meta tag below.
<meta name="referrer" content="no-referrer"> <!-- don't send HTTP referer for privacy purpose and to use Google Maps Geocoding API without key -->

Starting June 11, 2018, you can no longer use GoogleMaps API without key.
source

I am able to put location indicator in websites without any api key or javascript code
I use Fancybox to show a google maps modal box very easily.
<head>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.6/dist/jquery.fancybox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.6/dist/jquery.fancybox.min.js"></script>
</head>
<body>
<a data-fancybox="" data-options="{"iframe" : {"css" : {"width" : "80%", "height" : "80%"}}}" href="https://www.google.com/maps/search/?api=1&query=centurylink+field" class="btn btn-primary">Open Modal Map</a>
</body>

Related

How to migrate google sheets API v3 to google sheets Api v4

I've been using a public google spreadsheet as a JSON endpoint for several of my web projects for some time now. I liked this approach because I could retrieve data from a public spreadsheet without needing any kind of authentication or tokens to get the data, all I needed to do was publish the spreadsheet and then fetch from a simple URL:
fetch(`https://spreadsheets.google.com/feeds/${mode}/${id}/${sheetNum}/public/values?alt=json`).then((res)=>console.log(res));
Google is deprecating sheets v3, and I'm confused about how to migrate to v4. From this answer I gather that I need to provide an access token which is created via the google cloud console. But do I need to create some kind of special "app" or "workplace" or will any old API token do? I tried the following:
Create a GCP project
Enable Google Sheets API
Hit Create Credentials
fetch data using the following URL scheme:
fetch(https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/RANGE?key=API_KEY)
But this is giving me a 403 response.
You are using the JSON Alt Type variant of the Google Data protocol. This protocol is dated and appears to no longer work reliably. The GData API Directory tells:
Google Spreadsheets Data API: GData version is still live. Replaced by the Google Sheets API v4.
Google Sheets API v4 is a modern RESTful interface that is typically used with a client library to handle authentication and batch processing of data requests. If you do not want to do a full-blown client implementation, David Kutcher offers the following v4 analog for the GData JSON Alt Type, using jQuery:
GData (old API, not recommended):
var url = 'https://spreadsheets.google.com/feeds/list/' +
spreadsheet_id + '/' + tab_ordinal + '/public/values?alt=json';
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
V4 (new API, recommended):
var url = 'https://sheets.googleapis.com/v4/spreadsheets/' +
spreadsheet_id + '/values/' + tab_name +
'?alt=json&key=' + api_key;
($.getJSON(url, 'callback=?')).success(function(data) {
// ...
};
...where:
spreadsheet_id is the long string of letters and numbers in the address of the spreadsheet — it is the bit between /d/ and /edit
tab_ordinal is number of the sheet — the first sheet that appears in the tab bar is sheet number 1, the second one is 2, and so on
tab_name is the name of the sheet, i.e., the name you see in the tab bar at the bottom of the window when you have the spreadsheet open for editing
api_key is the API key you get from from Google Cloud Platform console
Note that the JSON output format differs between the two versions.
The old GData JSON Alt Type variant API requires that the spreadsheet is made public through File > Publish to the web. V4 requires that the file is shared with "anyone with the link can view" through File > Share.
FINDINGS
The URL scheme produces the error 403 because mostly likely the spreadsheet file isn't shared publicly like this:
I can also replicate the 403 error when my test sheet isn't shared publicly using the same URL scheme:
RECOMMENDATION:
You can double check the spreadsheet file you're accessing and check it's sharing permission, making sure it's set to Anyone with the link:
TEST RESULT
Publicly shared test sheet
After setting up the spreadsheet file's sharing permission to Anyone with the link using the same v4 URL scheme:

Do I need to hide API key when using google maps js API? If so, how? [duplicate]

This question already has answers here:
How do I securely use Google API Keys
(2 answers)
Closed last month.
According to https://developers.google.com/maps/documentation/javascript/tutorial#HTML5 ,
it seems I can add the following tag to my html and start using maps js API.
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
But this will reveal my API key.
After searching on google and browsing answers on stackoverflow, I feel that maybe there is no need to hide this API key. I just need to set the referer when I create the API key on google, as explained in
https://stackoverflow.com/a/2256312/1316649
So, even others know my API key, they cannot use it from another domain. Am I right?
But google says you shouldn't embed API key in code:
https://support.google.com/cloud/answer/6310037
So, do I need to hide API key when using google maps js API? If so, how?
Update: By 'API key', I meant browser API key.
You can create multiple API keys with different restrictions to use them safely. For embedding a map, the Google Maps documentation has instructions for creating a correctly restricted API key so that it cannot be abused for other purposes at Get an API Key - Restricting API keys. It's OK to include a restricted API key in your source code, because you cannot embed a map properly without doing that anyway.
If you need server-side API access, you can create a second API key with less restrictions. That one should be kept secret.
While the above answers are helpful, none of them addresses the following vulnerability:
Once a user has access to your API key, even if they are restricted to using it only from your domain, they can still use it as much as they want. In the crudest sense, this could mean a million page refreshes (and map loads) in a very small amount of time, consequently putting you over your usage quota.
I haven't come across any solutions that address this issue. Unless I'm missing something...?
Relevant usage limits for google maps javascript api here.
The link that you posted that says you shouldn't embed API keys in code is related to Google's Cloud Platform. You are fine to leave your API key for Google Maps in your code.
To hide an API key for any service:
Design a web server that will accept requests for the third party service and proxy requests to them.
Design your interface to make requests to the web server that you designed in step 1.
Store the key on the web server you built in step 1, and apply authentication, authorization and rate limiting to the 3rd party proxied requests.
The 3rd party libraries that you use might to build and interface in step 2 might force you to use certain hosts or might force you to include an API key. For the first problem, you'll have to either edit their library code, or provide the 3rd party client library with a different http request library, like redefining the fetch() function in javascript for example. For the second problem, just add a garbage key and your proxy server can ignore it and re-write it with the real key.
Benefits:
Hide your keys.
Track who, what, and when for requests and responses. You could do this other ways though.
Could add a layer of caching to the service to speed up requests that other users have made before, provided that their terms of service allows it.
Caveats:
Because users will be making requests pretending to be your server, you are accepting a security risk. If the user intentionally makes maliciously formatted requests, they are doing so while appearing to be your server. You can however log all requests if you want to audit them later.
It takes more than a couple seconds to build and configure the proxy server with all the security you require.
You now need to handle all of these web requests which may be a lot of traffic.
You may want to intercept the responses the server returns in case it returns the key in the response body during in an error or otherwise.
You are adding another link in the chain and it will make the service slightly less reliable.
Mentions
I wanted to mention that this is essentially what "#OLTO and SUGI-cube Project" was trying to demonstrate in their answer and what #Brandon Miller was suggesting as a solution in a comment.
No need to hide API key, you just have to make it useless,
You can simply use key restrictions on the google API console.
from google API console choose:-
credentials
choose your API key or create a new one
Application restrictions
HTTP referrers (websites)
and then add your Website restrictions
I would recomend restricting your API keys to only be used by the IP addresses & referrer URLs that need them: By restricting the IP addresses, referrer URLs, you can reduce the impact of a compromised API key.
You can specify the hosts and apps that can use each key from the console by opening the Credentials page and then either creating a new API key with the settings you want, or editing the settings of an API key.
This should help you to secure your API keys.
Jeff
The two most accepted ways I have seen are to either use the [#googlemaps/js-api-loader]1 Or to - and this is important - restrict your keys the way google tells you to.
Hello there,
Even if it's too late to post an answer I believe this would help the community, so i have worked out a solution that will hide the script tag from the DOM, I managed to do it by deleting the script tag after loading the script OR if it were an error while loading it,
So here is the proposed solution and I'm happy to hear from you if it doesn't fit:
<script>
const deleteMapScriptTag = () => {
document.body.removeChild(
Array.from(document.body.getElementsByTagName('script')).find(
(item) =>
item.src.includes('https://maps.googleapis.com/maps/api/js?key=')
)
)
}
</script>
So that part will search for the google maps script tag and remove it from the document, and we will call it after the
onload, onerror
events provided by the script tag as demonstrated below :
<script onload="deleteMapScriptTag()" onerror="deleteMapScriptTag()"
src="https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&libraries=places"></script>
this will remove the script tag from the DOM as soon as it loads or fails loading, preventing users from inspecting the file and acquiring your key.
Although removed from the DOM, the original script tag (and therefore the key) will still be visible when viewing the page source.
Additionally, the full URL of the script can also be inspected via the Network requests panel in developer tools which also exposes the API key.
You need to hide API key
You need to hide API key when using google maps js API. It is not enough for you to set the referer.
I have local web server on my PC and can change my hosts file, So that I can spoof domain name of my HTML as your domain.
If you reveal your API key in your HTML, someone might access Google map with that key. This could mean a million page refreshes (and map loads)!
This is bad example from Google.
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
How to hide API key from HTML
I use Environment Variables and CGI to hide my API key from HTML as follows.
1. set Environment Variables
I set Google Maps API key in Environment Variables and passing it to my CGI scripts.
nginx + fcgiwrap are running on my server, so I set API key in my fcgiwrap.conf like this.
fcgiwrap.conf
location /cgi-bin/ {
........
fastcgi_param GOOGLE_MAPS_API_KEY  YOUR_API_KEY; <= SET YOUR API KEY HERE
}
2. make CGI script
I made python CGI like this. This is same as src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY in SAMPLE of Google.
getapijs.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import os
url = 'https://maps.googleapis.com/maps/api/js'
key = os.environ['GOOGLE_MAPS_API_KEY'] # get Environment Variables
mysrc = url + "?key=" + key
response = requests.get(mysrc) # get src from Google Maps url
print("'Content-Type': 'text/javascript; charset=UTF-8'") # header for HTML
print("")
print(response.text)
3. call CGI from javascript
call your CGI from window.onload. This is same as <script defer ... &callback=initMap> in SAMPLE from Google.
main.js
function initMap() {
var uluru = {lat: -25.344, lng: 131.036};
var map = new google.maps.Map(document.getElementById('map'), {zoom: 4, center: uluru});
var marker = new google.maps.Marker({position: uluru, map: map});
}
window.onload = function() {
fetch("/cgi-bin/getapijs.py").then(res=>{
return res.text();
}).then(mytext => {
eval(mytext);
}).then(() => {
initMap();
}).catch(() =>{
// error handling
});
}
4.read main.js in your HTML
set <script src="main.js"></script> in your header section.
index.html
<!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
<title>Hello World</title>
<script src="main.js"></script>
</head>
<body>
<h3>My Google Maps Demo</h3>
<!--The div element for the map -->
<div id="map"></div>
</body>
</html>

Google API Key for browser. Issue when referrers set

I generated Browser API Key in Google Console and set referrers:
Then I go to http://afriflirt.com, open JS console in browser and run this code ("Google Maps Geocoding API" enabled for this api key in settings):
var apiKey = 'AIzaSyAGpR-mG46fDbmWjJwkZZHft_xvZ_dM3cA';
$.getJSON(
'https://maps.googleapis.com/maps/api/geocode/json?address=12345&key=' + apiKey,
function(resp) {alert(JSON.stringify(resp));}
);
in response I see this message:
This IP, site or mobile application is not authorized to use this API
key. Request received from IP address 113.180.75.109, with referer:
http://afriflirt.com/
If I remove referrers - API key start working, but this is not safe.
So it's a problem only when I set referrers. Tried different formats of referrers patterns, but nothing worked. Also tried to wait some time (as I saw "it may take up to 5 minutes for settings to take effect"), but it doesn't help too.
Please let me know if you have any ideas how to fix this.
According to the documentation, you need a server key for the geocoding web service.
Create a server key, enable it for IP address: 113.180.75.109, that should work in your example (but it isn't recommended to use a server key from javascript like that, use a browser key and the Google Maps Javascript API v3 Geocoding Service).

How to allow users to see my Google Analytics chart data without undergoing authentication/Sign In process

I am using the Google Analytics Javascript library to let users view a GeoMap of the particular page they are on. However, everytime they attempt to do so, thye have to go through an authentication process only to have my data displayed on my page. How can I find an alternative to this. I only want to embed my Analytics data through a visualized graph on my page so that all anonymous viewers can see it. This is the code where the process takes place.
google.setOnLoadCallback(init);
/**
* This is called once the Google Data JavaScript library has been loaded.
* It creates a new AnalyticsService object, adds a click handler to the
* authentication button and updates the button text depending on the status.
*/
function init()
{
myService = new google.gdata.analytics.AnalyticsService('charts_sample');
/*
this is essentially the line I want to replace. It anonymously
tries to access my viewer's account.I want to set this scope such as it
address the URI of my Analytics account
*/
scope = 'https://www.google.com/analytics/feeds';
/*
if the above scope is altered to my URI then the below unnecessary login
steps will not be required at all. This is the reason why my viewers are
taken to their analytics page which is fundamentally non-existent.
*/
$("authButton").onclick = function() {
// Test if the user is not authenticated.
if (!google.accounts.user.checkLogin(scope))
{
// Authenticate the user.
google.accounts.user.login(scope);
} else
{
// Log the user out.
google.accounts.user.logout();
getStatus();
}
}
getStatus();
}
// gets the account data and then gets the outputs of the requested query
function getStatus()
{
getAccountFeed();
getDataFeed();
}
function getAccountFeed()
{
//Here agsain, I want to modify it access my account's URI
var myFeedUri ='https://www.google.com/analytics/feeds/accounts/default?max-results=50';
myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);
}
function getDataFeed()
{
var myMapPopularityFeedUri = 'https://www.google.com/analytics/feeds/data?ids=ga%3A53482361&dimensions=ga%3ApagePath%2Cga%3Acity%2Cga%3Acountry%2Cga%3Aregion%2Cga%3Alongitude%2Cga%3Alatitude&metrics=ga%3Avisitors&start-date=2011-12-01&end-date=2011-12-25&max-results=50';
myService.getDataFeed(myMapPopularityFeedUri, handleDataFeed, handleError);
}
Help will be appreciated a lot. Please don't be too critical. Its my first question here. Instead let me know and I will make for my amendments.
Here is a screenshot of what the embed looks like upon my own click, i.e, after GA has
fetched my own data through my account. The geoMap is at the bottom of the page.
It seems the best way is creating of the separate shared (public) feed (report) in Analytics.
Just feed security requires authorization login to view or receive data if the feed (report) was created under personal credentials ... independently to what version OAuth or OAuth2 is used, just if you use request to view data on the site you should use at least API key (for public reports) OR OAuth credentials for personal reports.
look this guide:
Loading an API and Making a Request
or choose any other example from this page:
Google Analytics: Core Reporting API Client Libraries & Sample Code (v3)
Use this nice tool also:
OAuth 2.0 Playground
Generate API key for maps:
Google Maps API Family
Google Maps JS API tutorial:
Google Maps JavaScript API V3
Have you looked at using oAuth2 for the Authorization?

How can I access Google Sheet spreadsheets only with Javascript?

I want to access Google Spreadsheets using JavaScript only (no .NET, C#, Java, etc.)
I came here and was shocked to know that there is NO API for JavaScript to access Google Sheets.
Please tell me how to access (CREATE/EDIT/DELETE) Google Sheets using JavaScript or any of its frameworks like jQuery.
I have created a simple javascript library that retrieves google spreadsheet data (if they are published) via the JSON api:
https://github.com/mikeymckay/google-spreadsheet-javascript
You can see it in action here:
http://mikeymckay.github.com/google-spreadsheet-javascript/sample.html
Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.
It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 2 (correction, 3) ways to do this today:
As mentioned in the answer by Dan Dascalescu, you can use Google Apps Script, the JavaScript-in-Google's-cloud solution. That is, non-Node server-side JS apps outside the browser that run on Google servers.
You code your apps in the Apps Script code editor, and they can access Google Sheets in two different ways:
The Spreadsheet Service (native object support; usage guide); native is easier but is generally older than...
The Google Sheets Advanced Service (directly access the latest Google Sheets REST API [see below]; usage guide)
Apps Script also powers add-ons, and you can extend Sheets UI functionality with Sheets add-ons (like these)
You can even write mobile add-ons which extend the Sheets app on Android
To learn more about using Apps Script, check out these videos I've created (most involve the use of Sheets)
You can also use the Google APIs Client Library for JavaScript to access the latest Google Sheets REST API on the client side.
Here are some generic samples of using the client library
The latest Sheets API (v4) was released at Google I/O 2016; it's much more powerful than all previous versions, giving developers programmatic access to most features found in the Sheets UI
Here is the JavaScript quickstart for the API to help you get started
Here are sample "recipes" (JSON payloads) for core API requests
If you're not "allergic" to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with more "real-world" samples of using the API you can learn from and migrate to JS if desired (NOTE: even though it's Python code, most API requests have JSON & easily portable to JS):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Those and others in the Sheets API video library
The 3rd way to access Google APIs with JavaScript is from the Node.js client library on the server-side. It works similarly to using the JavaScript (client) client library described just above, only you'll be accessing the same API from the server-side. Here's the Node.js Quickstart example for Sheets. You may find the Python-based videos above to be even more useful as they too access the API from the server-side.
When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.
Here's the Gist.
You can create a spreadsheet using the Google Sheets API. There is currently no way to delete a spreadsheet using the API (read the documentation). Think of Google Docs API as the route to create and look-up documents.
You can add/remove worksheets within the spreadsheet using the worksheet based feeds.
Updating a spreadsheet is done through either list based feeds or cell based feeds.
Reading the spreadsheet can be done through either the Google Spreadsheets APIs mentioned above or, for published sheets only, by using the Google Visualization API Query Language to query the data (which can return results in CSV, JSON, or HTML table format).
Forget jQuery. jQuery is only really valuable if you're traversing the DOM. Since GAS (Google Apps Scripting) doesn't use the DOM jQuery will add no value to your code. Stick to vanilla.
I'm really surprised that nobody has provided this information in an answer yet. Not only can it be done, but it's relatively easy to do using vanilla JS. The only exception being the Google Visualization API which is relatively new (as of 2011). The Visualization API also works exclusively through a HTTP query string URI.
There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.
First up, you need an Google API key. Head here:
https://developers.google.com/places/web-service/get-api-key
NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037
Get all data for a spreadsheet - warning, this can be a lot of data.
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true
Get sheet metadata
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}
Get a range of cells
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}
Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.
var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";
axios.get(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2016 update: The easiest way is to use the Google Apps Script API, in particular the SpreadSheet Service. This works for private sheets, unlike the other answers that require the spreadsheet to be published.
This will let you bind JavaScript code to a Google Sheet, and execute it when the sheet is opened, or when a menu item (that you can define) is selected.
Here's a Quickstart/Demo. The code looks like this:
// Let's say you have a sheet of First, Last, email and you want to return the email of the
// row the user has placed the cursor on.
function getActiveEmail() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var activeRow = activeSheet.getActiveCell().getRow();
var email = activeSheet.getRange(activeRow, 3).getValue();
return email;
}
You can also publish such scripts as web apps.
edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date
information.
It looks lke you can, but it's a pain to use. It involves using the Google data API.
http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html
"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."
and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/
'JavaScript accessing Google Docs' would be tedious to implement and moreover Google documentation is also not that simple to get it. I have some good links to share by which you can achieve js access to gdoc:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs
http://code.google.com/apis/spreadsheets/gadgets/
http://code.google.com/apis/gdata/docs/js.html
http://www.mail-archive.com/google-help-dataapi#googlegroups.com/msg01924.html
May be these would help you out..
Sorry, this is a lousy answer. Apparently this has been an issue for almost two years so don't hold your breath.
Here is the official request that you can "star"
Probably the closest you can come is rolling your own service with Google App Engine/Python and exposing whatever subset you need with your own JS library. Though I'd love to have a better solution myself.
In this fast changing world most of these link are obsolet.
Now you can use Google Drive Web APIs:
Java
PHP
Javacript
.NET
Python
Ruby
and others...
you can do it by using Sheetsee.js and tabletop.js
example from git
another Example
You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:
https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html
Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).
Some example code (this example makes an RGraph chart):
<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>
<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>
<script>
// Create a new RGraph Sheets object using the spreadsheet's key and
// the callback function that creates the chart. The RGraph.Sheets object is
// passed to the callback function as an argument so it doesn't need to be
// assigned to a variable when it's created
new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
{
// Get the labels from the spreadsheet by retrieving part of the first row
var labels = sheet.get('A2:A7');
// Use the column headers (ie the names) as the key
var key = sheet.get('B1:E1');
// Get the data from the sheet as the data for the chart
var data = [
sheet.get('B2:E2'), // January
sheet.get('B3:E3'), // February
sheet.get('B4:E4'), // March
sheet.get('B5:E5'), // April
sheet.get('B6:E6'), // May
sheet.get('B7:E7') // June
];
// Create and configure the chart; using the information retrieved above
// from the spreadsheet
var bar = new RGraph.Bar({
id: 'cvs',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxisLabels: labels,
xaxisLabelsOffsety: 5,
colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
yaxis: false,
marginLeft: 40,
marginBottom: 35,
marginRight: 40,
key: key,
keyBoxed: false,
keyPosition: 'margin',
keyTextSize: 12,
textSize: 12,
textAccessible: false,
axesColor: '#aaa'
}
}).wave();
});
</script>
For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

Categories

Resources