Google Analytics Easy Dashboard Javascript Library

This document describes how to use the ga-ez-dash library version 1.0.

Table of Contents

Overview

This library is designed to create an easy way to build a custom Google Analytics Dashboard on your own page. The library is built on top of the Google Analytics Core Reporting and Chart Tools APIs and does all the heavy lifting of handling authorization, issuing queries, and transforming the results into pretty visualizations.

Note: At this time, each user who views a dashboard must have access to the Google Analytics account from which the dashboard data is generated. Currently you can not create a dashboard for users who do not have access to your Google Analytics data.

Getting Started

We tried to make this library very easy to use. To get started you need to perform the following 3 steps:

  1. Register for a developer key
  2. Copy & Paste the code to a web page
  3. Configure the chart

Register

All applications that use the Google Analytics API must be registered through the Google APIs Console. When you register in the console, you will create a new project and configure the settings to work with this library. Once configured, the console will provide you with a few values that you need in the configuration step. Here's exactly what you need to do:

  1. Go to the Google APIs Console
  2. Navigate to the left panel to Services -> Analytics API
  3. And switch service to ON

Next you will need to configure this project to use OAuth 2.0 authentication. Just like you need to login to your Google Analytics account to view your data, you will need to authorize this dashboard application to view your data. Authorization is handled through the OAuth2.0 protocol.

This dashboard library implements most of the OAuth functionality. As a user, all you need to do is configure your project in the APIs to use OAuth2.0, then use the Client ID and API Key provided in the console as parameters when you configure the library.

Getting your Client ID and API Key

In the Google APIs Console, for the project you just created:

  1. Navigate on the left panel to API Access
  2. Click the big blue Create An OAuth 2.0 Client ID button

    Create OAuth 2.0 button in google apis console

  3. Add a cool product name and logo, then click Next
  4. Under:
  5. Click Create Client ID

Note: This dashboard library will only work if the script the page is on is hosted from a web server. The domain (hostname) of the web server must match the values in the JavaScript origins field. This library will not work if it is hosted from a file.

Once complete, your project should have values where the red arrows are in this image.

image of Google APIs Cosole APIs access page pointing out Client ID and API Key locations

Copy or write down the Client ID and API Key values. You will use both later in the configuration stage.

Once compete, time to copy and paste the code to a page.

  1. Copy the library and save to your server
  2. Fire up your favorite text / html editor
  3. Copy and paste the following code into a blank page
<!DOCTYPE>
<html>
<head><title>GA Dash Demo</title></head>
<body>

  <!-- Add Google Analytics authorization button -->
  <button id="authorize-button" style="visibility: hidden">
        Authorize Analytics</button>

  <!-- Div element where the Line Chart will be placed -->
  <div id='line-chart-example'></div>

  <!-- Load all Google JS libraries -->
  <script src="https://www.google.com/jsapi"></script>
  <script src="gadash-1.0.js"></script>
  <script src="https://apis.google.com/js/client.js?onload=gadashInit"></script>
  <script>
    // Configure these parameters before you start.
    var API_KEY = 'Enter Your API Key Here';
    var CLIENT_ID = 'Enter Your Client ID Here';
    var TABLE_ID = 'Enter your Table ID here';
    // Format of table ID is ga:xxx where xxx is the profile ID.

    gadash.configKeys({
      'apiKey': API_KEY,
      'clientId': CLIENT_ID
    });

    // Create a new Chart that queries visitors for the last 30 days and plots
    // visualizes in a line chart.
    var chart1 = new gadash.Chart({
      'type': 'LineChart',
      'divContainer': 'line-chart-example',
      'last-n-days':30,
      'query': {
        'ids': TABLE_ID,
        'metrics': 'ga:visitors',
        'dimensions': 'ga:date'
      },
      'chartOptions': {
        height:600,
        title: 'Visits in January 2011',
        hAxis: {title:'Date'},
        vAxis: {title:'Visits'},
        curveType: 'function'
      }
    }).render();
  </script>
</body>
</html>

Once complete, save this file to your server.

Configure

Once you've copied and pasted the code, you just need to configure the chart to work with your data.

Replace the API_KEY and CLIENT_ID values with the respective API Key and Client ID that you created in the Google APIs console during the first step.

Replace the TABLE_ID parameter with ga: + your profile ID. Finding your profile ID is easy. Just log into Google Analytics and navigate to the profile you want to use. After logging in, there will be a profile ID at the end of the URL in the address bar after the 'p'. This is your profile ID. Example: p'XXXX'.

URL of a Google Analytics. The last p query parameter has the profile ID.

Use ga: + your profile ID to get your Table ID. So if your profile ID was 8325, your table id would be ga:8325.

Save the file. You're done!

Usage

Navigate your browser to the URL this script is hosted on. The script will:

  1. Display a button asking for you to authorize
  2. Click the button. You will be prompted to login and authorize access
  3. Once complete, the script will retrieve visitors over the past 30 days, and display the data in a pretty line chart

Great Success!

Chart Method Reference

Chart objects support 3 methods.

new gadash.Chart(opt_config)

To create a new chart you use the constructor:

var myChart = new gadash.Chart();

The constructor also accepts an optional configuration object as a parameter:

var myChart = new gadash.Chart({
  'query': {
    'ids': 'ga:1234',
    'start-date': '2012-01-01',
    'end-date': '2012-01-15',
    'metrics': 'ga:vists'
  }
});

A deep copy of the object passed into the constructor is made, then stored in the chart object. This allows the original object to be modified without effecting the values stored in the chart.

set(config)

Sets a configuration object in the chart:

myChart.set({
  'divContainer': 'chart1'
});

This method performs a deep copy of the object being passed into the method. So in the following example:

var config = {'divContainer': 'chart1'};
myChart.set(config);
config.divContainer = 'chart2';

The value of divContainer in myChart will be chart1.

The set method also extends keys that contain objects as values. So in the example:

var dimensions = {
  'query': {
    'dimensions': 'ga:source,ga:medium'
  }
};

var metrics = {
  'query': {
    'metrics': 'ga:visits,ga:pageviews'
  }
};

myChart.set(dimensions).set(metrics);

The first set stores the query in the chart. Because query is an object, the second set adds the metrics to the query object. (as opposed to overwriting the original query object.)

render()

Renders this chart by executing the API query, handing the response, converting the GA API response into a Google Visualization data table, getting a new visualization object, and finally drawing the visualization on the page.

chart1.render();

Note: Each of these methods return an instance to the chart object. This allows you to chain methods. For example: myChart.set(conig1).set(config2).render()

Configuration Parameter Reference

You can now continue configuring this chart to query for different data, or to display the data in other Google Visualizations. All configurations are done through the configuration object you pass into the Chart constructor. Use the following table to see how the various chart options work.

Name Type Description
type

Required
String

Specifies which type of chart instance to use from the Google Visualization's library. To use a chart, specify the object name of the chart from the visualization library. You can use any available chart the visualization library offers but these are the valid charts that have been tested:

'LineChart'
'BarChart'
'ColumnChart'
'PieChart'
'Table'

Note: If type is not declared, then the default chart is a 'Table'.

Example: The following will declare a Line Chart from the Google Visualization library.

'type': 'LineChart'
divContainer

Required
String Specifies which div element to display the chart in.

Example: This example will draw the chart to <div id='chart1'></div>

'divContainer': 'chart1'
query

Required
Object

Object that specifies a query object for Google Analytics Core Reporting a API. The query object must contain following parameters: ids, start-date, end-date, metrics. The following parameters are optional: dimensions, filters, max-results, segment, sort, start-index, fields

Note: If last-n-days is declared in the config, then start-date and end-date are not required parameters of the query option because they will be already declared.

start-date and end-date must be a String of in the form yyyy-MM-dd

For a list of all valid metrics and dimensions, see the Dimensions & Metrics Reference

For more detailed information about the query object and supported parameters, see Core Reporting API Reference Guide

Example: The following query will return the number of visitors for each day from January 1, 2000 to January 31, 2000

query: {
  'ids':'ga:1234',
  'metrics': 'ga:visitors',
  'start-date':'2000-01-01',
  'end-date':'2000-01-30',
  'dimensions': 'ga:date'
}
chartOptions

Optional
Object

Object that specifies chart options configuation parameters. This object must be configured based on the type parameter that was passed.

'type':'LineChart' refer to Line Chart Configurations
'type':'BarChart' refer to Bar Chart Configurations
'type':'ColumnChart' refer to Column Chart Configurations
'type':'PieChart' refer to Pie Chart Configurations
'type':'Table' refer to Table Configurations

Example: This example is to configure the chart options of a LineChart. Sets the div's height of the line chart to 600, the title of the chart to "Visits in January 2011", the x-axis label to "Date", and the y-axis label to "Visits"

chartOptions: {
  height:600,
  title: 'Visits in January 2011',
  hAxis: {title:'Date'},
  vAxis: {title:'Visits'},
  curveType: 'function'
}
last-n-days

Optional
Number

Sets the query parameters start-date and end-date to query data from the last n days passed to it.

Note: This parameter will always override the start-date and end-date of the query object.

Example: This will query Google Analytics data from the last 30 days.

'last-n-days': 30
onSuccess

Optional
Function Allows a user to define their own callback function after the query is executed. It gives users the ability to use their own chart APIs and flexibility with Analytics data. This function takes in a Google Analytics JSON response object. For information about the response object, see Google Analytics API Console

Example: This is an example of a custom callback that gets total visitors from the GA response then continues to render the chart and use the default callback.

<-- HTML snippet to update -->
<p>Total visits = <span id="totalVisits"></span>.</p>
// callback defined in configuration object.
'onSuccess': function(response) {
  var totalVisits = response.totalsForAllResults['ga:visits'];

  // Update UI.
  document.getElementById('totalVisits').innerHTML = totalVisits;

  // Continue rendering the chart as normal.
  // Note: this points to the instance of the Chart object from which the
  //       onSuccess function is called.
  this.defaultOnSuccess(response);
}
onError

Optional
Function

Allows user to handle errors by creating their own error function. The function takes in a String with the message.

Example: Will print the error message in an alert window instead of a div on the HTML page.

'onError': function(message) {
  alert(message);
}

Changelog

May 14, 2012

April 10, 2012





G-Unit