-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyticsCharts.js
696 lines (607 loc) · 22.4 KB
/
analyticsCharts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// Copyright 2010 Google Inc. All Rights Reserved.
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview This file contains all javascript used by analyticsCharts.html
* to generate visual charts with data populated by the Google Analytics Export
* API.
* @author api.alexl@google.com (Alexander Lucas)
*/
// Load the Google data JavaScript client library.
google.load('gdata', '2.x', {packages: ['analytics']});
// Set the callback function when the library is ready.
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');
scope = 'https://www.google.com/analytics/feeds';
var button = document.getElementById('authButton');
// Add a click handler to the Authentication button.
button.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();
}
/**
* Utility method to display the user controls if the user is
* logged in. If user is logged in, get Account data and
* get Report Data buttons are displayed.
*/
function getStatus() {
var getAccountButton = document.getElementById('getAccount');
getAccountButton.onclick = getAccountFeed;
var getDataButton = document.getElementById('getData');
getDataButton.onclick = getDataFeed;
var dataControls = document.getElementById('dataControls');
var loginButton = document.getElementById('authButton');
if (!google.accounts.user.checkLogin(scope)) {
dataControls.style.display = 'none'; // hide control div
loginButton.innerHTML = 'Access Google Analytics';
} else {
dataControls.style.display = 'block'; // show control div
loginButton.innerHTML = 'Logout';
}
}
/**
* Main method to get account data from the API.
*/
function getAccountFeed() {
var myFeedUri =
'https://www.google.com/analytics/feeds/accounts/default?max-results=50';
myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);
}
/**
* Handle the account data returned by the Export API by constructing the inner
* parts of an HTML table and inserting into the HTML file.
* @param {object} result Parameter passed back from the feed handler.
*/
function handleAccountFeed(result) {
// An array of analytics feed entries.
var entries = result.feed.getEntries();
// Create an HTML Table using an array of elements.
var outputTable = ['<table><tr>',
'<th>Account Name</th>',
'<th>Profile Name</th>',
'<th>Profile ID</th>',
'<th>Table Id</th></tr>'];
// Iterate through the feed entries and add the data as table rows.
for (var i = 0, entry; entry = entries[i]; ++i) {
// Add a row in the HTML Table array for each value.
var row = [
entry.getPropertyValue('ga:AccountName'),
entry.getTitle().getText(),
entry.getPropertyValue('ga:ProfileId'),
entry.getTableId().getValue()
].join('</td><td>');
outputTable.push('<tr><td>', row, '</td></tr>');
}
outputTable.push('</table>');
// Insert the table into the UI.
document.getElementById('visitorsDiv').innerHTML =
outputTable.join('');
}
/**
* Main method to get report data from the Export API.
*/
function getDataFeed() {
var myFeedUri = ['https://www.google.com/analytics/feeds/data',
'?start-date=2010-06-01',
'&end-date=2012-06-10',
'&dimensions=ga:day,ga:visitorType',
'&metrics=ga:visits',
'&sort=ga:day',
'&max-results=20',
'&ids=', document.getElementById('tableId').value].join('');
myService.getDataFeed(myFeedUri, handleDataFeed, handleError);
var myBounceFeedUri = ['https://www.google.com/analytics/feeds/data',
'?start-date=2010-06-01',
'&end-date=2012-06-10',
'&dimensions=ga:day',
'&metrics=ga:bounces,ga:entrances',
'&sort=ga:day',
'&max-results=10',
'&ids=', document.getElementById('tableId').value].join('');
myService.getDataFeed(myBounceFeedUri, handleBounceFeed, handleError);
var myTopContentUri = ['https://www.google.com/analytics/feeds/data',
'?start-date=2010-06-01',
'&end-date=2012-06-10',
'&dimensions=ga:pagePath',
'&metrics=ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits',
'&sort=-ga:pageviews',
'&ids=', document.getElementById('tableId').value].join('');
myService.getDataFeed(myTopContentUri, handleTopContentFeed, handleError);
}
/**
* Handle the data returned by the Export API for the Visitors by VisitorType
* query, by converting the query into an image URL for a chart, and embedding
* that chart within the HTML.
* inner parts of an HTML table and inserting into the HTML File.
* @param {object} result Parameter passed back from the feed handler.
*/
function handleDataFeed(result) {
document.getElementById('visitorsDiv').innerHTML = '';
var gaChartData = getVisitorChartData(result);
//
// var barChart = getBarChart(gaChartData);
// drawChart('visitorsDiv', barChart.getURL());
//
// var lineChart = getLineChartFromBarChart(barChart);
// drawChart('visitorsDiv', lineChart.getURL());
var pieChart = getPieChart(gaChartData);
drawChart('visitorsDiv', pieChart.getURL());
}
/**
* Handle the data returned by the Export API for the Visitors by VisitorType
* query, by converting the query into an image URL for a chart, and embedding
* that chart within the HTML.
* inner parts of an HTML table and inserting into the HTML File.
* @param {object} result Parameter passed back from the feed handler.
*/
function handleTopContentFeed(result) {
document.getElementById('topcontentDiv').innerHTML = '';
var gaChartData = getTopContentChartData(result);
//
// var barChart = getBarChart(gaChartData);
// drawChart('visitorsDiv', barChart.getURL());
//
// var lineChart = getLineChartFromBarChart(barChart);
// drawChart('visitorsDiv', lineChart.getURL());
var barChart = getTopContentBarChart(gaChartData);
drawChart('topcontentDiv', barChart.getURL());
}
/**
* Handle the data returned by the Export API for the Entrances VS Bounces
* query by converting the query into an image URL for a chart, and embedding
* that chart within the HTML.
* @param {object} result Parameter passed back from the feed handler.
*/
function handleBounceFeed(result) {
document.getElementById('entrancesDiv').innerHTML = '';
var chartData = getBounceChartData(result);
// Initializes settings for the chart - type, width, colors, etc. Sets to a
// grouped bar chart.
var chart = getEBChart(chartData);
drawChart('entrancesDiv', chart.getURL());
// How does it look as a line graph? Easy to find out. Just change the chart
// type, and update the HTML.
chart.setParam('cht', 'lc');
drawChart('entrancesDiv', chart.getURL());
// We can even turn this into a compound chart very easily.
// The following parameters need to be changed.
chart.setParams({
'chm': 'D,0033FF,1,0,5,1', // add a line marker. Reference here:
'cht': 'bvg', // change base chart type to bar chart
// t1 denotes that the base chart should only render the first dataset.
// The second dataset is being reserved for the line.
'chd': chart.getParam('chd').replace('t', 't1')
});
drawChart('entrancesDiv', chart.getURL());
}
/**
* Given the max value that will appear in the chart, this method
* determines a good max value and increment size for the chart, such that it's
* easy to read. This is a very basic algorithm that starts off with a max
* chart value one order of magnitude larger than the value passed in (for
* instance, for 123 it will set a chart max of 1000), and then reduces that
* chart max to a point where it can be cleanly divided into 5 increments, and
* the value passed in is greater than 1/2 of the chart max.
* @param {int} currMax The maximum value that will be displayed in the chart.
* @return {array} A two-item array containing the max chart value, and
* suggested increment.
*/
function getScaleData(currMax) {
var result = [0, 0];
// Determine order of magnitude (number of digits left of decimal).
var magnitude = Math.log(currMax) / Math.LN10;
magnitude = Math.ceil(magnitude);
var newMax = Math.pow(10, magnitude);
if (newMax / 5 > currMax) {
newMax = newMax / 5;
}
while (newMax > (currMax * 2)) {
newMax = newMax / 2;
}
var step = newMax / 5;
result[0] = newMax;
result[1] = step;
return result;
}
/**
* Helper method to fill up arrays so they remain the same size.
* Helpful for situations like data over time, where values might not be
* returned for specific dates in one array, but they are for the other, so the
* sizes must be kept in sync.
* @param {array} firstArray the first array that needs to be synced in size.
* @param {array} secondArray the second array that needs to be synced in size.
*/
function fillToSameSize(firstArray, secondArray) {
if (firstArray.length < secondArray.length) {
firstArray.push(0);
} else if (secondArray.length < firstArray.length) {
secondArray.push(0);
}
}
/**
* Populates the chart data object with data from the "visitor type" query.
* for simplicity, dimension / metric names are hardcoded.
* @param {object} result The object containing the response from the API call.
* @return {object} An object holding all data to be used in creating the chart.
*/
function getVisitorChartData(result) {
var entries = result.feed.getEntries();
var returningVisitors = [];
var newVisitors = [];
var days = [];
var maxReturningVisitors = 0;
var maxNewVisitors = 0;
for (var i = 0, entry; entry = entries[i]; ++i) {
var visType = entry.getValueOf('ga:visitorType');
var numVisits = entry.getValueOf('ga:visits');
var day = parseInt(entry.getValueOf('ga:day'), 10); // convert to base 10
// Because the Export API will not include entries for a dimension with no
// data on a particular day, it's important to make sure the visitor arrays
// stay in sync with the days array. We do this using the helper method
// "fillToSameSize", which makes sure that if only one type of visitor was
// recorded for a specific day, 0's are filled in for the other visitor type
// on that same day.
if (!days.length) {
days.push(day);
} else {
var lastDay = days[days.length - 1];
if (day != lastDay) {
days.push(day);
fillToSameSize(newVisitors, returningVisitors);
}
}
if (visType == 'New Visitor') {
newVisitors.push(numVisits);
maxNewVisitors = Math.max(maxNewVisitors, numVisits);
} else {
returningVisitors.push(numVisits);
maxReturningVisitors = Math.max(maxReturningVisitors, numVisits);
}
}
fillToSameSize(newVisitors, returningVisitors);
return {
'returningVisitors': returningVisitors,
'newVisitors': newVisitors,
'maxNewVisitors': maxNewVisitors,
'maxReturningVisitors': maxReturningVisitors,
'days': days
};
}
/**
* Populates chart data object with data from "entrances and bounces" query.
* for simplicity, dimension / metric names are hardcoded.
* @param {object} result The object containing the response from the api call.
* @return {object} An object holding all data to be used in creating the chart.
*/
function getTopContentChartData(result) {
var entries = result.feed.getEntries();
var entrances = [];
var bounces = [];
var days = [];
var maxEntrances = 0;
var maxBounces = 0;
var result = {};
for (var i = 0, entry; entry = entries[i]; ++i) {
var pageUrl = entry.getValueOf('ga:pagePath');
var pageViews = entry.getValueOf('ga:pageViews');
console.log('URL ' + pageUrl);
console.log('Count ' + pageViews);
result[pageUrl] = pageViews;
}
return result;
}
/**
* Populates chart data object with data from "entrances and bounces" query.
* for simplicity, dimension / metric names are hardcoded.
* @param {object} result The object containing the response from the api call.
* @return {object} An object holding all data to be used in creating the chart.
*/
function getBounceChartData(result) {
var entries = result.feed.getEntries();
var entrances = [];
var bounces = [];
var days = [];
var maxEntrances = 0;
var maxBounces = 0;
for (var i = 0, entry; entry = entries[i]; ++i) {
var day = entry.getValueOf('ga:day');
var currEntrances = entry.getValueOf('ga:entrances');
maxEntrances = Math.max(currEntrances, maxEntrances);
var currBounces = entry.getValueOf('ga:bounces');
maxBounces = Math.max(currBounces, maxBounces);
days.push(parseInt(day, 10));
entrances.push(currEntrances);
bounces.push(currBounces);
}
return {
'maxValue': Math.max(maxBounces, maxEntrances),
'bounces': bounces,
'entrances': entrances,
'days': days
};
return chartData;
}
/**
* Sets up chart metadata (chart type, title, legend, etc) for a bar chart.
* @param {object} chartData The object holding all data to be used in creating
* the chart.
* @return {object} Chart object representing the chart to be drawn.
*/
function getTopContentBarChart(chartData) {
var chart = getChartObj();
// var returningVisitorsStr = chartData.returningVisitors.join(',');
// var newVisitorsStr = chartData.newVisitors.join(',');
// var maxValue = chartData.maxReturningVisitors + chartData.maxNewVisitors;
//
// scaleData = getScaleData(maxValue);
var legend = "Empty";
var values = 0;
for (key in chartData) {
legend += "|" + key;
values += "|" + chartData[key];
}
// Set chart meta-data
chart.setParams({
'chs': '500x150', // Image dimensions
'chxt': 'x,y', // Axes
'chts': '000000,15', // Title Style
'cht': 'bvg', // Chart Type (Bar, Vertical, Stacked)
'chco': 'a3d5f7|389ced', // Colors
'chbh': 'a,5,20', // Width & Spacing
'chm': 'N,FF0000,-1,,12', // Markers
'chtt': 'Top+Pages', // Title
'chdl': legend, // Legend
'chd': 't:' + values, // Chart Data
'chxl': '0:|' + legend, // Axis Labels
'chds': '0,' + 200, // Scaling
'chxr': '1,0,' + 200 // Axis Scaling
});
return chart;
}
/**
* Sets up chart metadata (chart type, title, legend, etc) for a bar chart.
* @param {object} chartData The object holding all data to be used in creating
* the chart.
* @return {object} Chart object representing the chart to be drawn.
*/
function getBarChart(chartData) {
var chart = getChartObj();
var returningVisitorsStr = chartData.returningVisitors.join(',');
var newVisitorsStr = chartData.newVisitors.join(',');
var maxValue = chartData.maxReturningVisitors + chartData.maxNewVisitors;
scaleData = getScaleData(maxValue);
// Set chart meta-data
chart.setParams({
'chs': '500x150', // Image dimensions
'chxt': 'x,y', // Axes
'chts': '000000,15', // Title Style
'cht': 'bvs', // Chart Type (Bar, Vertical, Stacked)
'chco': 'a3d5f7,389ced', // Colors
'chbh': 'a,5,20', // Width & Spacing
'chm': 'N,FF0000,-1,,12', // Markers
'chtt': 'Visitors+By+Type', // Title
'chdl': 'Returning+Visitors|New+Visitors', // Legend
'chd': 't:' + returningVisitorsStr + '|' + newVisitorsStr, // Chart Data
'chxl': '0:|' + chartData.days.join('|'), // Axis Labels
'chds': '0,' + scaleData[0], // Scaling
'chxr': '1,0,' + scaleData.join(',') // Axis Scaling
});
return chart;
}
/**
* Small helper method, gets the sum of values in an array.
* @param {array} input An array of numbers.
* @return {number} The sum of the array.
*/
function getArraySum(input) {
var total = 0;
for (var i = 0; i < input.length; i++) {
total += input[i];
}
return total;
}
/**
* Sets up chart metadata (chart type, title, legend, etc) for a pie chart.
* @param {object} chartData The object holding all data to be used in creating
* the chart.
* @return {object} Chart object representing the chart to be drawn.
*/
function getPieChart(chartData) {
var chart = getChartObj();
var newVisitors = getArraySum(chartData.newVisitors);
var returningVisitors = getArraySum(chartData.returningVisitors);
chartData.maxValue = returningVisitors + newVisitors;
chart.setParams({
'chs': '500x150', // Image dimensions
'chts': '000000,15', // Title Style
'cht': 'p3', // Chart Type
'chco': 'a3d5f7,389ced', // Colors
'chtt': 'Visitors+By+Type', // Title
'chdl': 'Returning+Visitors|New+Visitors', // Legend
'chd': 't:' + returningVisitors + ',' + newVisitors, // Chart Data
'chl': returningVisitors + '|' + newVisitors, // Labels
'chds': '0,' + chartData.maxValue // Max Value
});
return chart;
}
/**
* Sets up chart metadata (chart type, title, legend, etc) for
* entrances/bounces chart (starts off as a bar chart).
* @param {object} chartData The object holding all data to be used in creating
* the chart.
* @return {object} Chart object representing the chart to be drawn.
*/
function getEBChart(chartData) {
var chart = getChartObj();
var bouncesStr = chartData.bounces.join(',');
var entrancesStr = chartData.entrances.join(',');
scaleData = getScaleData(chartData.maxValue);
chart.setParams({
'chs': '500x150', // Image dimensions
'chxt': 'x,y', // axes
'chts': '000000,15', // Title Style
'cht': 'bvg', // Chart Type (Bar, Vertical, Grouped)
'chco': 'a3d5f7,389ced', // Colors
'chbh': 'a,5,20', // Width/Spacing
'chtt': 'Entrances+vs+Bounces', // Title
'chdl': 'Entrances|Bounces', // Legend
'chd': 't:' + entrancesStr + '|' + bouncesStr, // Chart Data
'chxl': '0:|' + chartData.days.join('|'), // Axis Labels
'chds': '0,' + scaleData[0], // Scaling
'chxr': '1,0,' + scaleData.join(',') // Axis Scaling
});
return chart;
}
/**
* Inserts an image tag into the DOM, inside an HTML tag specified by ID,
* and with the image sourced to a specified URL.
* @param {string} parentElementId The ID of the DOM element to insert the
* image tag into.
* @param {string} url The URL to use as the source of the inserted image.
*/
function drawChart(parentElementId, url) {
document.getElementById(parentElementId).innerHTML +=
'<img src="' + url + '" /><br />';
}
/**
* Using a bar chart object as a starting point, creates and returns a line
* chart object with the same internal dataset. Helper method meant to show
* how easy converting between the two chart types is.
* @param {object} barChart Bar chart wrapper used as basis for the line chart.
* @return {object} A line chart object.
*/
function getLineChartFromBarChart(barChart) {
var lineChart = getChartObj();
lineChart.setParams(barChart.getParams());
lineChart.setParam('cht', 'lc');
lineChart.setParam('chm', '');
return lineChart;
}
/**
* Alert any errors that come from the API request.
* @param {object} e The error object returned by the Analytics API.
*/
function handleError(e) {
var error = 'There was an error!\n';
if (e.cause) {
error += e.cause.status;
} else {
error.message;
}
alert(error);
}
/**
* Abstracts much of what is similar between different chart types out into
* a convenient wrapper object. The object has an internal set of all chart
* parameters types used in this example application, as well as methods for
* getting/setting those parameters, and converting them into a URL used to pull
* the image of the resulting chart.
* @return {object} Chart wrapper object representing the chart to be displayed,
* including all the relevant data and configuration options.
*/
function getChartObj() {
var params_ = {
'chs': '', // Image Dimensions
'chtt': '', // Title
'chxt': '', // Axes
'chts': '', // Title Style
'cht': '', // Chart type
'chd': '', // Data
'chdl': '', // Legend
'chco': '', // Colors
'chbh': '', // Width and spacing
'chxl': '', // Axis Labels
'chds': '', // Scaling
'chxr': '', // Axis Scaling
'chm': '', // Chart Markers
'chl': '' // Data Labels
};
var baseURL_ = 'http://chart.apis.google.com/chart';
/**
* Method to get all the parameters of a chart object.
* @return {object} An object containing all the key/value pairs that make up
* this chart object.
*/
function getParams_() {
return params_;
}
/**
* Method to get the value of a specific chart parameter by name.
* @param {string} key The name of the parameter to return.
* @return {string} The current value of the chart parameter specified by key.
*/
function getParam_(key) {
return params_[key];
}
/**
* Sets a parameter. Only does so if the key is already defined in the
* "params_" member variable. Otherwise the parameter is ignored and discarded.
* @param {string} key The name of the parameter being set.
* @param {string} val The value to insert at the specified key.
*/
function setParam_(key, val) {
if (params_[key] !== undefined) {
params_[key] = val;
}
}
/**
* Sets multiple parameters at once. Each key/value pair is only inserted if
* the key is defined in the "params_" member variable. Otherwise the parameter
* is ignored and discarded.
* @param {string} obj Object made up of key/value pairs to be set in this
* object.
*/
function setParams_(obj) {
for (key in obj) {
setParam_(key, obj[key]);
}
}
/**
* Given a base URL and an array of parameters, construct the complete URL.
* @return {string} The complete URL for the chart.
*/
function getURL_() {
paramArray = [];
for (key in params_) {
if (params_[key]) {
pairStr = [key, params_[key]].join('=');
paramArray.push(pairStr);
}
}
paramStr = paramArray.join('&');
url = [baseURL_, paramStr].join('?');
return url;
}
return {
'getParam': getParam_,
'getParams': getParams_,
'setParam': setParam_,
'setParams': setParams_,
'getURL': getURL_
};
}