Skip to content

Instantly share code, notes, and snippets.

@marchawkins
Created May 21, 2014 04:32
Show Gist options
  • Save marchawkins/23537f343ba96123988d to your computer and use it in GitHub Desktop.
Save marchawkins/23537f343ba96123988d to your computer and use it in GitHub Desktop.
How to connect to the Google Calendar API via the Javascript Client Library to retrieve calendar events. The demo also employs Oauth2 authentication, so the script could read a logged in user's calendar. This demo **only** reads a public calendar. You need the calendar's id (from google) in your own code to retrieve any events. For more info, vi…
<div class="row">
<div class="col-md-2 col-sm-2 col-xs-12">
<button id="authorize-button" style="visibility: hidden" class="btn btn-primary">Authorize</button>
</div><!-- .col -->
<div class="col-md-10 col-sm-10 col-xs-12">
<script type="text/javascript">
// date functions
Date.prototype.getWeek = function(start) {
start = start || 0;
var today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
var date = today.getDate() - day;
var StartDate = new Date(today.setDate(date));
var EndDate = new Date(today.setDate(date + 6));
return [StartDate, EndDate];
}
// set Dates to the start & end days of the week
var Dates = new Date().getWeek();
// calculate today's date
var today = new Date();
today = today.toISOString();
// google api console clientID and apiKey (https://code.google.com/apis/console/#project:568391772772)
var clientId = 'YOUR_GOOGLE_CLIENT_ID';
var apiKey = 'YOUR_GOOGLE_API_KEY';
// enter the scope of current project (this API must be turned on in the google console)
var scopes = 'https://www.googleapis.com/auth/calendar.readonly';
// Oauth2 functions
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
// show/hide the 'authorize' button, depending on application state
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
var resultPanel = document.getElementById('result-panel');
var resultTitle = document.getElementById('result-title');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden'; // if authorized, hide button
resultPanel.className = resultPanel.className.replace( /(?:^|\s)panel-danger(?!\S)/g , '' ) // remove red class
resultPanel.className += ' panel-success'; // add green class
resultTitle.innerHTML = 'Application Authorized' // display 'authorized' text
makeApiCall(); // call the api if authorization passed
} else { // otherwise, show button
authorizeButton.style.visibility = '';
resultPanel.className += ' panel-danger'; // make panel red
authorizeButton.onclick = handleAuthClick; // setup function to handle button click
}
}
// function triggered when user authorizes app
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// function load the calendar api and make the api call
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() { // load the calendar api (version 3)
var request = gapi.client.calendar.events.list({
'calendarId': 'mlb_22_%50hiladelphia+%50hillies#sports@group.v.calendar.google.com', // calendar ID
'maxResults': 20, // show max of 20 events
'singleEvents': true, // split recurring events into individual events
'timeMin': today, // start showing events starting at today
'timeMax': Dates[1], // end showing events this week (saturday)
'orderBy': 'startTime' // order events by their start time
});
// handle the response from our api call
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) { // loop through events and write them out to a list
var li = document.createElement('li');
var eventInfo = resp.items[i].summary + ' ' +resp.items[i].start.dateTime;
li.appendChild(document.createTextNode(eventInfo));
document.getElementById('events').appendChild(li);
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div class="panel panel-danger" id="result-panel">
<div class="panel-heading">
<h3 class="panel-title" id="result-title">Application Not Authorized</h3>
</div><!-- .panel-heading -->
<div class="panel-body">
<p>Upcoming Philadelphia Phillies games&hellip;</p>
<ul id="events"></ul>
</div><!-- .panel-body -->
</div><!-- .panel -->
</div><!-- .col -->
</div><!-- .row -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment