Skip to content

Instantly share code, notes, and snippets.

@saetia
Created June 26, 2012 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saetia/2997708 to your computer and use it in GitHub Desktop.
Save saetia/2997708 to your computer and use it in GitHub Desktop.
Google analytics
function initializeGoogleAnalytics(){
GoogleAnalytics.init();
}
var GoogleAnalytics = {
accountId: null,
accessToken: null,
getAccountId: function(){
return (this.accountId) ? 'ga:'+this.accountId : null;
},
getAccessToken: function(){
return (this.accessToken) ? this.accessToken : null;
},
isAuthorized: function(){
return (this.getAccessToken) ? true : false;
},
init: function(){
var now = new Date();
if (window.localStorage.helm_access_token && (now.getTime() - window.localStorage.helm_last_accessed) < 3600){
GoogleAnalytics.accessToken = window.localStorage.helm_access_token;
window.localStorage.helm_last_accessed = now.getTime();
GoogleAnalytics.accountId = window.localStorage.helm_property_id;
$.publish('GoogleAnalytics.authorized');
return true;
}
$.ajax(window.location.href, {
data: {do:'generate_google_access_token'}
}).done(function(data, textStatus, jqXHR){
if (data.status === 'OK'){
GoogleAnalytics.accessToken = data.access_token;
GoogleAnalytics.accountId = data.property_id;
window.localStorage.helm_last_accessed = now.getTime();
window.localStorage.helm_access_token = data.access_token;
window.localStorage.helm_property_id = data.property_id;
$.publish('GoogleAnalytics.authorized');
gapi.client.setApiKey(apiKey);
//window.setTimeout(this.checkAuth,1);
} else {
alert(data.error);
}
});
},
checkAuth: function(){
//alert('check auth');
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, GoogleAnalytics.handleAuthResult);
},
handleAuthResult: function(authResult) {
//alert('handleAuthResult');
var authorizeButton = document.getElementById('authorize-button');
console.dir(authResult);
if (authResult) {
GoogleAnalytics.accessToken = authResult.access_token;
authorizeButton.style.display = 'none';
GoogleAnalytics.displayGoogleAccounts();
} else {
console.error('failed to authorize via google');
authorizeButton.style.display = 'block';
authorizeButton.onclick = GoogleAnalytics.handleAuthClick;
}
},
handleAuthClick: function(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, this.handleAuthResult);
return false;
},
displayGoogleAccounts: function(){
if (!window.localStorage.analyticsAccounts || window.location.hash){
var restRequest = gapi.client.request({
'path': '/analytics/v3/management/accounts/~all/webproperties/~all/profiles'
});
restRequest.execute(function(response){
if (!window.localStorage.analyticsAccounts){
window.localStorage.analyticsAccounts = JSON.stringify(response);
}
var table = document.getElementById('accounts-template').innerHTML;
var compiled = _.template(table);
var accountView = document.getElementById('accounts-view');
accountView.innerHTML = compiled(response);
accountView.style.display = 'block';
GoogleAnalytics.chooseDefault();
});
} else {
var response = JSON.parse(window.localStorage.analyticsAccounts);
var table = document.getElementById('accounts-template').innerHTML;
var compiled = _.template(table);
var accountView = document.getElementById('accounts-view');
accountView.innerHTML = compiled(response);
accountView.style.display = 'block';
GoogleAnalytics.chooseDefault();
}
// if (window.localStorage.analyticsAccounts){
// var analyticsAccounts = JSON.parse(window.localStorage.analyticsAccounts);
// restRequest.execute(analyticsAccounts);
// }
},
chooseDefault: function(){
GoogleAnalytics.accountId = 12468211;
//shop900 12468211;
//metropolis 1615392
//shop900 41941416;
$('#accounts-view').hide();
$.publish('GoogleAnalytics.authorized');
}
};
var RangePicker = {
from: window.localStorage.startDate || null,
to: window.localStorage.endDate || null,
getFrom: function(){
return (this.from) ? this.from : '-1m';
},
getTo: function(){
return (this.to) ? this.to : '+0 d';
},
getFromDateObject: function(){
//RangePicker.from
if ($('.orders_date_range.from','#time_chooser_choose').hasClass('hasDatepicker')){
return new XDate($('.orders_date_range.from','#time_chooser_choose').datepicker('getDate'));
} else {
if (RangePicker.from){
return new XDate(RangePicker.from);
} else {
var fromDate = new XDate();
return fromDate.addMonths(-1);
}
}
},
getToDateObject: function(){
if ($('.orders_date_range.to','#time_chooser_choose').hasClass('hasDatepicker')){
return new XDate($('.orders_date_range.to','#time_chooser_choose').datepicker('getDate'));
} else {
if (RangePicker.to){
return new XDate(RangePicker.to);
} else {
return XDate();
}
}
}
};
var WidgetToolbox = {
cachedNames: [],
columnName: function(name){
if (this.cachedNames[name])
return this.cachedNames[name];
var pretty = name.replace('ga:','').replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
this.cachedNames[name] = pretty;
return pretty;
},
formatColumnType: function(type,value){
switch(type){
case 'STRING':
return value.toString();
break;
case 'CURRENCY':
return accounting.formatMoney(value).toString();
case 'FLOAT':
case 'INTEGER':
return accounting.formatNumber(value).toString();
break;
}
},
columnType: function(type){
/*
string
number
boolean
date
datetime
timeofday
*/
switch(type){
case 'STRING':
return 'string';
break;
case 'CURRENCY':
case 'FLOAT':
case 'INTEGER':
return 'number';
break;
}
}
};
/*
var dt = new google.visualization.DataTable(
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
},
0.6
)
The following example creates a new, empty DataTable and then populates it manually with the same data as above:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows([
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', {v:7, f:'7.000'}]
]);
*/
function Widget(params){
this.path = '/analytics/v3/data/ga';
this.data = null;
//do not remove –– needed for automatic init call
this.isDashboardWidget = true;
this.isDateBased = function(){
return (params.period) ? true : false;
};
this.getPeriod = function(){
return (params.period) ? params.period[0] : null;
};
//get the name of the init variable
this.getName = function(){
for (var v in window)
if (this == window[v]) return v;
};
var defaults = {
//'dimensions': 'ga:browser',
//'filters': 'ga:isMobile==No',
//sort': '-ga:visits',
'columns': [],
'metrics': 'ga:pageviews',
'max-results' : 1000,
'chart' : (this.isDateBased()) ? 'line' : 'table',
preprocess: function(data){
return data;
}
};
if (!params.sort){
if (!params.metrics){
defaults.sort = '-ga:pageviews';
} else {
defaults.sort = '-'+params.metrics.split(',')[0];
}
}
if (this.isDateBased()){
if (typeof(params.dimensions) !== 'undefined'){
params.dimensions = ','+params.dimensions;
} else {
params.dimensions = '';
}
}
switch(this.getPeriod()){
case 'm':
params.dimensions = 'ga:year,ga:month'+params.dimensions;
break;
case 'y':
params.dimensions = 'ga:year'+params.dimensions;
break;
case 'w':
params.dimensions = 'ga:year,ga:week'+params.dimensions;
break;
case 'd':
params.dimensions = 'ga:date'+params.dimensions;
break;
}
this.params = $.extend(defaults, params);
this.willRequestDataFromGoogle = function(){
if (!GoogleAnalytics.getAccountId()) return false;
if (!GoogleAnalytics.getAccessToken()) return false;
return true;
};
this.init = function(){
var widgetName = this.getName();
if (!document.getElementById(widgetName)){
var widgetTemplate = _.template(document.getElementById('widget-template').innerHTML);
$('.widgets:first').prepend(widgetTemplate({name: widgetName, id: widgetName}));
}
//widgetName
var startDate = RangePicker.getFromDateObject().toString('yyyy-MM-dd');
var endDate = RangePicker.getToDateObject().toString('yyyy-MM-dd');
$.extend(this.params,{
'start-date': startDate,
'end-date': endDate,
'access_token': GoogleAnalytics.getAccessToken(),
'ids': GoogleAnalytics.getAccountId()
});
//console.dir(this.params);
if (!this.willRequestDataFromGoogle()) {
console.error('Blocked: willRequestDataFromGoogle()');
return false;
}
//set up test routine here:::
//if (window.path.)
console.groupCollapsed(widgetName+' Request');
console.dir(this.params);
console.groupEnd(widgetName+' Request');
var request = gapi.client.request({
'path': this.path,
'params': this.params
});
var __widget = this;
request.execute(
function(response){
__widget.respond(response);
}
);
};
this.respond = function(response){
var widgetName = this.getName();
console.groupCollapsed(widgetName+' Response');
console.dir(response);
console.groupEnd(widgetName+'Response');
if (response.error){
$.each(response.error.errors, function(i, error) {
if (error.message === 'Invalid Credentials' || error.message === 'Login Required'){
window.localStorage.helm_access_token = null;
//GoogleAnalytics.init();
return false;
}
console.error(error.reason+': '+error.message);
});
return false;
};
this.data = new google.visualization.DataTable();
/*
date based when:
if period is weekly, monthly, daily or yearly
chart type is pie, geo, scatter, gauge, bubble
year:
group = 2012
year / month:
group = 2012-02
year / month / day:
group = 2012-02-05
year / month / day / week:
group = 'Feb 1st, 2012' #the week of
*/
var columns = [];
var columnHeaders = [];
var columnData = {};
//loop through each column header
for (var i = 0; i < response.columnHeaders.length; ++i) {
var column = {
dataType: WidgetToolbox.columnType(response.columnHeaders[i].dataType),
columnType: response.columnHeaders[i].columnType,
name: WidgetToolbox.columnName(response.columnHeaders[i].name)
};
columnHeaders.push(response.columnHeaders[i].name);
columnData[response.columnHeaders[i].name] = column;
if (this.params.columns.length){
for (var s = 0; s < this.params.columns.length; ++s)
columns[s] = this.params.columns[s].split(',');
} else {
//metrics
columns = this.params.dimensions.split(',');
}
//console.dir(columns);
//this.data.addColumn(column.dataType, column.name);
}
// console.group('columns');
// console.dir(columns);
// console.groupEnd('columns');
//add our date column
if (this.isDateBased()){
switch(this.getPeriod()){
case 'm':
this.data.addColumn('date', 'Month');
break;
case 'y':
this.data.addColumn('date', 'Year');
break;
case 'd':
this.data.addColumn('date', 'Date');
break;
case 'w':
if (_.contains(['bar','column'],this.params.chart)){
this.data.addColumn('string', 'Week');
} else {
this.data.addColumn('date', 'Week');
}
break;
}
//generate a list of every date we will be looking at
//between our date picker
var from = RangePicker.getFromDateObject();
var to = RangePicker.getToDateObject();
var date_range = [];
var range_of_all_dates = []; //bobo
var date_range_row = [];
switch(this.getPeriod()){
case 'm':
var time_diff = Math.ceil(from.diffMonths(to));
console.error(time_diff+' months');
for (r = 0; r <= time_diff; r++){
var monthsToAdd = (r) ? 1 : 0;
adjusted_date = from.addMonths(monthsToAdd);
var added_date = adjusted_date.toString('yyyy-MM-dd');
date_range.push(added_date);
date_range_row[r] = [];
console.error(added_date);
for (c = 0; c < columns.length; c++)
date_range_row[r][c] = [added_date];
}
break;
case 'y':
var time_diff = Math.ceil(from.diffYears(to));
break;
case 'd':
var time_diff = Math.ceil(from.diffDays(to));
break;
case 'w':
var time_diff = Math.ceil(from.diffWeeks(to));
for (r = 0; r <= time_diff; r++){
var weeksToAdd = (r) ? 1 : 0;
adjusted_date = from.addWeeks(weeksToAdd);
week_start = new XDate(adjusted_date.getFullYear(), 0);
week_start.setWeek(adjusted_date.getWeek());
var added_date = week_start.toString('yyyy-MM-dd');
date_range.push(added_date);
date_range_row[r] = [];
for (c = 0; c < columns.length; c++)
date_range_row[r][c] = [week_start];
}
break;
}
// console.group('date range');
// console.dir(date_range);
// console.groupEnd('date range');
// console.group('date range row');
// console.dir(date_range_row);
// console.groupEnd('date range row');
} else {
var non_date_row = [];
//alert(widgetName+' = '+WidgetToolbox.columnName(this.params.metrics));
this.data.addColumn('string','Title');
this.data.addColumn('number',WidgetToolbox.columnName(this.params.metrics));
}
/*
for (var i = 0; i < response.rows.length; ++i) {
for (var c = 0; c < columns.length; ++c) {
console.error('AddColumn()');
}
//this.data.addRow([new Date(), first, second, third, fourth]);
}
*/
var date_ranges = [];
var column_labels = [];
//loop through and add columns for each tracked entity
//we're looking through columns for how to group this data.
for (var i = 0; i < response.rows.length; ++i) {
var row = response.rows[i];
// console.group('rows '+i);
// console.dir(row);
// console.groupEnd('rows '+i);
for (var c = 0; c < columns.length; ++c) {
if (this.isDateBased()){
switch(this.getPeriod()){
case 'w':
var parsedDate = new XDate(row[0], 0);
parsedDate.setWeek(row[1]);
//console.group('weekly date');
//console.dir(parsedDate.toString('yyyy-MM-dd')+' – week: '+row[1]);
//console.groupEnd('weekly date');
break;
case 'd':
var splitDate = row[0].split(/(\d{4})(\d{2})(\d{2})/).filter(Number);
var parsedDate = XDate(splitDate.join('-'));
//console.group('daily date');
//console.dir(parsedDate.toString('yyyy-MM-dd'));
//console.groupEnd('daily date');
break;
case 'm':
//ga:year,ga:month
var parsedDate = new XDate(row[0]+'-'+row[1]+'-01');
// var splitDate = row[0].split(/(\d{4})(\d{2})(\d{2})/).filter(Number);
// var parsedDate = XDate(splitDate.join('-'));
// console.error('–––––––––––––– <DAILY DATE> ––––––––––––––––––');
// console.dir(parsedDate.toString('yyyy-MM-dd'));
// console.error('–––––––––––––– </DAILY DATE> –––––––––––––––––');
break;
case 'y':
// var splitDate = row[0].split(/(\d{4})(\d{2})(\d{2})/).filter(Number);
// var parsedDate = XDate(splitDate.join('-'));
// console.error('–––––––––––––– <DAILY DATE> ––––––––––––––––––');
// console.dir(parsedDate.toString('yyyy-MM-dd'));
// console.error('–––––––––––––– </DAILY DATE> –––––––––––––––––');
break;
}
}
if (this.isDateBased()){
if (!column_labels[c]) column_labels[c] = ['Date'];
switch(this.getPeriod()){
case 'm':
if (_.contains(['ga:year','ga:month'],columns[c])) continue;
break;
case 'y':
if ('ga:year' === columns[c]) continue;
break;
case 'd':
case 'w':
if (_.contains(['ga:year','ga:week','ga:date'],columns[c])) continue;
break;
}
}
var columnTitle = [];
if (typeof columns[c] === 'object'){
for (var p = 0; p < columns[c].length; ++p) {
var index = _.indexOf(columnHeaders, columns[c][p]);
columnTitle.push($.trim(row[index]));
}
} else {
var index = _.indexOf(columnHeaders, columns[c]);
columnTitle.push($.trim(row[index]));
}
var metric_index = _.indexOf(columnHeaders, this.params.metrics);
var metric_value = row[metric_index];
var processed_data = this.params.preprocess({
label: columnTitle.join(' '),
value: Number(metric_value)
});
if (this.isDateBased()){
//if we havent stored this column name, add it. keeps things unique
if (!_.include(column_labels[c], columnTitle.join(' '))){
column_labels[c].push(columnTitle.join(' '));
this.data.addColumn('number', processed_data.label);
}
var column_label_index = _.indexOf(column_labels[c], columnTitle.join(' '));
var date_range_index = _.indexOf(date_range, parsedDate.toString('yyyy-MM-dd'));
date_range_row[date_range_index][c][column_label_index] = processed_data;
// console.group(widgetName+' ~ DATE RANGE');
// console.error(column_label_index);
// console.dir(date_range_row[date_range_index][c]);
// console.dir(processed_data);
// console.groupEnd(widgetName+' ~ DATE RANGE');
} else {
//not date-based
non_date_row.push(processed_data);
}
}
}
//pie charts
if (!this.isDateBased()){
for (var r = 0; r < non_date_row.length; r++) {
var processed_data = non_date_row[r];
var label = processed_data.label;
var value = processed_data.value;
var format = (processed_data.format) ? processed_data.format : accounting.formatNumber(value);
this.data.addRow();
this.data.setCell(r, 0, label);
this.data.setCell(r, 1, value, format);
}
}
//ever other type of chart
if (this.isDateBased()){
for (var r = 0; r < date_range_row.length; r++) {
this.data.addRow();
for (var c = 0; c < columns.length; c++) {
for (var l = 0; l < column_labels[c].length; l++) {
var processed_data = (date_range_row[r][c] && date_range_row[r][c][l]) ? date_range_row[r][c][l] : {label: null, value: null};
// if (widgetName === 'TimeOnSite' || widgetName === 'BounceRate'){
// console.group(widgetName+' processed data');
// console.dir(processed_data);
// console.groupEnd(widgetName+' processed data');
// }
//dates should not be string formated
if ('getTime' in processed_data){
var value = processed_data;
//column and bar do not support date fields
if (_.contains(['bar','column'], this.params.chart))
value = value.toString('MMM d, yyyy');
// if (widgetName === 'TimeOnSite' || widgetName === 'BounceRate'){
// }
this.data.setCell(r, l, value);
} else {
var value = processed_data.value;
var format = (processed_data.format) ? processed_data.format : accounting.formatNumber(value);
this.data.setCell(r, l, value, format);
}
}
}
}
} //datebased
//console.dir(this.data);
var $widget = $('#'+widgetName);
WidgetColors.container = $widget;
$widget.css('backgroundColor', WidgetColors.backgroundColor());
$widget.parents('section.widgets').css('backgroundColor', WidgetColors.rowBackgroundColor());
var chart_element = document.getElementById(widgetName);
switch(this.params.chart){
case 'area':
var chart = new google.visualization.AreaChart(chart_element);
break;
case 'pie':
var chart = new google.visualization.PieChart(chart_element);
break;
case 'bar':
var chart = new google.visualization.BarChart(chart_element);
break;
case 'bubble':
var chart = new google.visualization.BubbleChart(chart_element);
break;
case 'column':
var chart = new google.visualization.ColumnChart(chart_element);
break;
case 'candlestick':
var chart = new google.visualization.CandlestickChart(chart_element);
break;
case 'combo':
var chart = new google.visualization.ComboChart(chart_element);
break;
case 'gauge':
var chart = new google.visualization.Gauge(chart_element);
break;
case 'treemap':
var chart = new google.visualization.TreeMap(chart_element);
break;
case 'geo':
var chart = new google.visualization.GeoChart(chart_element);
break;
case 'table':
var chart = new google.visualization.Table(chart_element);
break;
case 'steppedarea':
var chart = new google.visualization.SteppedAreaChart(chart_element);
break;
case 'scatter':
var chart = new google.visualization.ScatterChart(chart_element);
break;
case 'line':
var chart = new google.visualization.LineChart(chart_element);
break;
default:
console.error('“'+this.params.chart+'” is not a valid chart type');
$widget.parents('.envelope').remove();
return false;
break;
}
var opts = {
forceIFrame: false,
//table
page: 'enable', //enable, event, disable
alternatingRowStyle: true,
showRowNumber: false,
firstRowNumber: 1,
allowHtml: true,
startPage: 0,
sort: 'enable', //enable, event, disable
sortColumn: 1,
sortAscending: false,
pageSize: 50,
cssClassNames: {
selectedTableRow: 'selectedTableRow',
oddTableRow: 'oddTableRow',
tableCell: 'tableCell',
headerCell: 'headerCell',
tableRow: 'tableRow',
headerRow: 'headerRow',
hoverTableRow: 'hoverTableRow'
},
title: null,
titlePosition: 'out',
is3D: true,
slices: {}, //slices: [{color: 'black', {}, {}, {color: 'red'}]
pieSliceBorderColor: WidgetColors.gridlineColor(),
pieSliceTextStyle: null, //{color: 'black'},
pieResidueSliceColor: WidgetColors.gridlineColor(),
pieResidueSliceLabel: 'Other',
sliceVisibilityThreshold: 1/70, // 1/720
tooltip: {
text: 'both',
textStyle: {
color: null
},
showColorCode: true,
trigger: 'hover'
},
//titleTextStyle: {color: 'black', fontName: <global-font-name>, fontSize: <global-font-size>}
width: $widget.width(),
height: $widget.height(),
chartArea: {
left: '15%',
top: '15%',
width: '80%',
height: '75%'
},
legend: {
position: 'top',
textStyle: {color:WidgetColors.axisTextColor()},
scrollArrows: {
activeColor: WidgetColors.axisTextColor(),
inactiveColor: WidgetColors.gridlineColor()
},
pagingTextStyle: {color: WidgetColors.axisTextColor()}
},
reverseCategories: false,
theme: 'maximized',
vAxis: {
baseline: 0,
logScale: false,
title: null,
minValue: 'automatic',
maxValue: 'automatic',
textPosition: 'out', //in, out, none
textColor: WidgetColors.axisTextColor(),
baseline: 0,
baselineColor: WidgetColors.baselineColor(),
gridlines: {color: WidgetColors.gridlineColor(), count: 10}, //{color: '#333', count: 4},
direction: 1,
viewWindowMode: 'pretty', //pretty, maximized, explicit
viewWindow: null //{min: 'auto', max: 'auto'}
},
hAxis: {
title: null,
titleColor: WidgetColors.axisTitleColor(),
textColor: WidgetColors.axisTextColor(),
baseline: 0,
baselineColor: WidgetColors.baselineColor(),
textPosition: 'out', //in, out, none
direction: 1,
gridlines: {color: WidgetColors.backgroundColor(), count: 0},
slantedText: false,
slantedTextAngle: 30, //1-90
maxAlternation: 2,
//showTextEvery:
//maxValue:
//minValue:
//viewWindowMode: 'pretty', //pretty, maximized, explicit
viewWindow: null //{min: 'auto', max: 'auto'}
},
interpolateNulls: true,
lineWidth: 3,
pointSize: 4,
//axisTitlesPosition: 'out',
curveType: 'function',
enableInteractivity: true,
focusTarget: 'datum',
fontName: 'sans-serif',
fontSize: 'automatic',
colors: WidgetColors.colors(),
titleColor: WidgetColors.titleColor(),
backgroundColor: {
fill: WidgetColors.backgroundColor(),
stroke: WidgetColors.gridlineColor(),
strokeWidth: 0,
},
legendTextColor: WidgetColors.legendTextColor(),
legendBackgroundColor: WidgetColors.legendBackgroundColor(),
legendTextColor: WidgetColors.legendTextColor(),
};
if (this.params.chart === 'pie'){
opts.chartArea.height = '90%';
opts.chartArea.width = '95%';
opts.legend.position = 'right';
}
// if (widgetName === 'BounceRate'){
// this.data = new google.visualization.DataView(this.data);
// this.data.setColumns([{calc: function(data, row) { return ''; }, type:'string'}, 0, 1]);
// }
chart.draw(this.data, opts);
/*
this.options.colors = WidgetColors.colors(),
this.options.gridlineColor = WidgetColors.gridlineColor();
this.options.titleColor = WidgetColors.titleColor();
this.options.backgroundColor = WidgetColors.backgroundColor();
this.options.legendTextColor = WidgetColors.legendTextColor();
this.options.legendBackgroundColor = WidgetColors.legendBackgroundColor();
this.options.legendTextColor = WidgetColors.legendTextColor();
this.options.hAxis = {};
this.options.vAxis = {};
this.options.hAxis.textColor = WidgetColors.axisColor();
this.options.vAxis.textColor = WidgetColors.axisColor();
this.options.hAxis.titleColor = WidgetColors.axisTitleColor();
this.options.vAxis.titleColor = WidgetColors.axisTitleColor();
this.options.hAxis.textColor = WidgetColors.axisTextColor();
this.options.vAxis.textColor = WidgetColors.axisTextColor();
this.options.vAxis.baselineColor = WidgetColors.baselineColor();
*/
/*
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: data,
options: {'title':widgetName, 'width':800, 'height':600},
containerId: widgetName+'_chart'
//, dataSourceUrl: 'http://spreadsheets.google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1'
});
wrapper.draw();
*/
};
}
$(document).ready(function(){
$('#accounts-view').on('click','tr',function(e){
GoogleAnalytics.accountId = $(this).data('id');
$('#accounts-view').hide();
});
});
$(document).ready(function(){
$('.datepicker.from').datepicker({defaultDate: '-1m'});
$('.datepicker.to').datepicker({});
});
/*
Combining Filters
Filters can be combined using OR and AND boolean logic. This allows you to effectively extend the 128 character limit of a filter expression.
OR
The OR operator is defined using a comma (,). It takes precedence over the AND operator and may NOT be used to combine dimensions and metrics in the same expression.
Examples: (each must be URL encoded)
Country is either (United States OR Canada):
ga:country==United%20States,ga:country==Canada
Firefox users on (Windows OR Macintosh) operating systems:
ga:browser==Firefox;ga:operatingSystem==Windows,ga:operatingSystem==Macintosh
AND
The AND operator is defined using a semi-colon (;). It is preceded by the OR operator and CAN be used to combine dimensions and metrics in the same expression.
Examples: (each must be URL encoded)
Country is United States AND the browser is Firefox:
ga:country==United%20States;ga:browser==Firefox
Country is United States AND language does not start with 'en':
ga:country==United%20States;ga:language!~^en.*
Operating system is (Windows OR Macintosh) AND browser is (Firefox OR Chrome):
ga:operatingSystem==Windows,ga:operatingSystem==Macintosh;ga:browser==Firefox,ga:browser==Chrome
Country is United States AND visits are greater than 5:
ga:country==United%20States;ga:visits>5
*/
/*
// https://www.googleapis.com/analytics/v3/management/accounts
{
"kind": "analytics#accounts",
"totalResults": 1,
"startIndex": 1,
"itemsPerPage": 1000,
"items": [
{
"id": "30481",
"kind": "analytics#account",
"selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/30481",
"name": "Google Store",
"created": "2005-06-10T22:48:30.000Z",
"updated": "2011-07-22T21:14:25.886Z",
"childLink": {
"type": "analytics#webproperties",
"href": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties"
}
}
]
}
// https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties
{
"kind": "analytics#webproperties",
"startIndex": 1,
"itemsPerPage": 1000,
"totalResults": 1,
"items": [
{
"id": "UA-30481-1",
"kind": "analytics#webproperty",
"selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1",
"accountId": "30481",
"internalWebPropertyId": "50530",
"websiteUrl": "www.googlestore.com",
"created": "2005-11-12T04:51:10.000Z",
"updated": "2011-07-12T23:51:12.327Z",
"parentLink": {
"type": "analytics#account",
"href": "https://www.googleapis.com/analytics/v3/management/accounts/30481"
},
"childLink": {
"type": "analytics#profiles",
"href": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1/profiles"
}
}
]
}
// https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1/profiles
{
"kind": "analytics#profiles",
"startIndex": 1,
"itemsPerPage": 1000,
"totalResults": 1,
"items": [
{
"id": "1174",
"kind": "analytics#profile",
"selfLink": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1/profiles/1174",
"accountId": "30481",
"webPropertyId": "UA-30481-1",
"internalWebPropertyId": "50530",
"name": "www.googlestore.com - goals & ecomm",
"currency": "USD",
"timezone": "America/Los_Angeles",
"defaultPage": "default.aspx",
"excludeQueryParameters": "sid, Go, price",
"siteSearchQueryParameters": "q",
"siteSearchCategoryParameters": "category",
"created": "2005-11-11T23:21:13.000Z",
"updated": "2011-07-22T21:14:25.886Z",
"parentLink": {
"type": "analytics#webproperty",
"href": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1"
},
"childLink": {
"type": "analytics#goals",
"href": "https://www.googleapis.com/analytics/v3/management/accounts/30481/webproperties/UA-30481-1/profiles/1174/goals"
}
}
]
}
// get all of the profiles for all accounts
// https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles
*/
/*
start-index
start-index=10
Optional.
If not supplied, the starting index is 1. (Result indexes are 1-based. That is, the first row is row 1, not row 0.) Use this parameter as a pagination mechanism along with the max-results parameter for situations when totalResults exceeds 10,000 and you want to retrieve rows indexed at 10,001 and beyond.
Back to Top
max-results
max-results=100
Optional.
Maximum number of rows to include in this response. You can use this in combination with start-index to retrieve a subset of elements, or use it alone to restrict the number of returned elements, starting with the first. If max-results is not supplied, the query returns the default maximum of 1000 rows.
The Analytics Core Reporting API returns a maximum of 10,000 rows per request, no matter how many you ask for. It can also return fewer rows than requested, if there aren't as many dimension segments as you expect. For instance, there are fewer than 300 possible values for ga:country, so when segmenting only by country, you can't get more than 300 rows, even if you set max-results to a higher value.
Back to Top
fields
fields=rows,columnHeaders(name,dataType)
Optional.
Specifies which fields to return in a partial response. If you only use a subset of the fields in the API response, you can use the fields parameter to specify which fields to include.
The format of the fields request parameter value is loosely based on XPath syntax. The supported syntax is summarized below.
Use a comma-separated list to select multiple fields.
Use a/b to select a field b that is nested within field a; use a/b/c to select a field c nested within b.
Use a sub-selector to request a set of specific sub-fields of arrays or objects by placing expressions in parentheses "( )".
For example: fields=columnHeaders(name,dataType) returns only the name and dataType fields in the columnHeaders array. You can also specify a single sub-field, where fields=columnHeader(name) is equivalent to fields=columnHeader/name.
Back to Top
prettyPrint
prettyPrint=false
Optional.
Returns the response in a human-readable format if true. Default value: false.
Back to Top
quotaUser
quotaUser=4kh4r2h4
Optional.
Lets you enforce per-user quotas from a server-side application even in cases when the user's IP address is unknown. This can occur, for example, with applications that run cron jobs on App Engine on a user's behalf. You can choose any arbitrary string that uniquely identifies a user, but it is limited to 40 characters.
This overrides userIp if both are provided.
*/
/*
Combining Filters:
The OR operator is defined using a comma (,). It takes precedence over the AND operator and may NOT be used to combine dimensions and metrics in the same expression.
The AND operator is defined using a semi-colon (;). It is preceded by the OR operator and CAN be used to combine dimensions and metrics in the same expression.
*/
/*
//cities in illinois
'params': {
'access_token': GoogleAnalytics.getAccessToken(),
'ids': 'ga:1615392',
//'dimensions': 'ga:region',
'dimensions': 'ga:city',
'metrics': 'ga:visits',
'filters': 'ga:region==Illinois',
//'metrics': 'ga:browser',
'start-date': fromString,
'end-date' : toString,
'max-results' : 99999
}
*/
//united states
/*
segment=gaid::-1
All Visits gaid::-1
New Visitors gaid::-2
Returning Visitors gaid::-3
Paid Search Traffic gaid::-4
Non-paid Search Traffic gaid::-5
Search Traffic gaid::-6
Direct Traffic gaid::-7
Referral Traffic gaid::-8
Visits with Conversions gaid::-9
Visits with Transactions gaid::-10
Mobile Traffic gaid::-11
Non-bounce Visits gaid::-12
*/
/*
Data Feed
title—the string Google Analytics Data for Profile, followed by the ID of the selected profile
id—the feed URL
totalResults—the total number of results for the query, regardless of the number of results in the response
startIndex—the starting index of the entries, which is 1 by default or otherwise specified by the start-index query parameter
itemsPerPage—the number of items in the current request, which is a maximum of 10,000
dxp:startDate—the first date for the query as indicated in the start-date query parameter
dxp:endDate—the ending date for the query as indicated in the end-date query parameter, inclusive of the date provided
dxp:containsSampledData—boolean value indicating whether any of the entries in this response contain sampled data. See Sampling below for details.
dxp:aggregates—contains the total values of each metric matched by the query. Some queries match more values in Google Analytics than can be returned by the API in a single page. When this happens, you will have to paginate through the results. The aggregate metric values contain the sum of each metric for the un-paginated data. This is different than the sum of the metric values returned in a single page, which the API does not return.
dxp:metric—metrics representing the total values of all metrics the query matched
name—the name of the metric
value—the un-paginated value of this metric
type—the type of the value returned. Can be: currency, float, percent, time, us_currency, an unknown type, or not set
dxp:dataSource—summary information about the Analytics source of the data
dxp:tableId —The unique, namespaced profile ID of the source, such as ga:1174
dxp:tableName—The name of the profile as it appears in the Analytics administrative UI
dxp:property name=ga:profileId—The profile ID of the source, such as 1174
dxp:property name=ga:webPropertyId—The web property ID of the source, such as UA-30481-1
dxp:property name=ga:accountName—The name of the account as it appears in the Analytics interface.
dxp:segment—For both default and custom advanced segments, the feed returns the name and ID associated with the segment. For dynamic segments, the feed returns the expression contained in the request.
entry—Each entry in the response contains the following elements
title—the list of dimensions in the query and the matching result for that entry
dxp:dimension—one element for each dimension in the query
name—the name of the dimension
value—the value of the dimension
dxp:metric—one element for each metric in the query
name—the name of the metric
value—the aggregate value for the query for that metric (e.g. 24 for 24 pageviews)
type—the type of the value returned. Can be: currency, float, percent, time, us_currency, an unknown type, or not set
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment