English | Site Directory

Google Visualization API

Developers Guide

Welcome to the developer documentation for the Google Visualization API. The Google Visualization JavaScript API lets you access structured data and visualize that data using JavaScript in your web pages. The Google Visualization API also enables creation of gadgets.

This API is new, and its feature set is largely determined by active involvement of its customers. Please join us in helping to shape the API and features by participating in the Google Visualization API discussion group to give feedback and discuss the API.

Table of Contents

Audience

This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. There are many JavaScript tutorials available on the Web.

Some parts of this documentation are designed for people familiar with gadgets.

Introduction

Google Visualization API is a JavaScript API for web developers and gadget developers to access and display tabular data from many sources, for example Google spreadsheets. This document describes how to read and display information from data sources that support the Google Visualization API.

The Visualization API addresses two common problems in data visualization:

  1. How to read data from multiple data sources using a single API.
  2. How to process the data without knowing about the data source implementation.

The API concepts are:

  1. All you need to know about a data source is it's URL. The underlying implementation of the data source is not exposed to the API users. The same API can be used to access different data sources.
  2. A query is sent to the data source to retrieve data.
  3. Data returned from a data source is a two-dimensional table with rows and columns, where each column has an associated data type.


With the Visualization API, you can send a query to a supported data source, and iterate over the response data table.

The "Hello World" of the Google Visualization API

The easiest way to start learning about this API is to see a simple example. The following example reads data from a Google Spreadsheet, and displays the data as a table:

<html>
  <head>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1");
      function initialize() {
        var query = new google.visualization.Query(DATA_SOURCE_URL);
        query.send(handleQueryResponse);  // Send the query with a callback function
      }
      google.setOnLoadCallback(initialize); // Set callback to run when API is loaded

      // Query response handler function.
      function handleQueryResponse(response) {

        if (response.isError()) {
          alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
          return;
        }

        var data = response.getDataTable(); 
        var html = [];
        html.push('<table border="1">');

        // Header row
        html.push('<tr><th>Seq</th>');
        for (var col = 0; col < data.getNumberOfColumns(); col++) {
          html.push('<th>' + escapeHtml(data.getColumnLabel(col)) + '</th>');
        }
        html.push('</tr>');

        for (var row = 0; row < data.getNumberOfRows(); row++) {
          html.push('<tr><td align="right">' + (row + 1) + '</td>');
          for (var col = 0; col < data.getNumberOfColumns(); col++) {
            html.push(data.getColumnType(col) == 'number' ? '<td align="right">' : '<td>');
            html.push(escapeHtml(data.getFormattedValue(row, col)));
            html.push('</td>');
          }
          html.push('</tr>');
        }
        html.push('</table>');

        document.getElementById('tablediv').innerHTML = html.join('');
      }

      function escapeHtml(text) {
        if (text == null)
          return '';

        return text.replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;');
      }

    </script>
  </head>

  <body>
    <div id="tablediv">Loading...</div>
  </body>
</html>

Include the Visualization API on Your Page

To include the Visualization API in your page, you need to both include the Google AJAX APIs script tag and call google.load("visualization", "1"):

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1");
  function initialize() {
    // Called once the Visualization API is loaded
  }
  google.setOnLoadCallback(initialize); // Set callback to run when API is loaded
</script>

The first script tag loads the google.load function, which lets you load individual Google APIs. Then, google.load("visualization", "1") loads Version 1 of the Visualization API. Currently the Visualization API is in Version 1, but new versions may be available in the future.

Sending the Query

Once the API is loaded, you can create and send a query to the data source. The data source is identified by a URL that is provided by the data source application. For example, to get the data source URL from a Google Spreadsheet, do the following:

  1. Open a spreadsheet.
  2. Insert a gadget, select the range of cell you want to read.
  3. In the gadget title, click the arrow icon on top right.
  4. select 'get query data-source URL' from the popup menu.


The data source URL for a Google Spreadsheet will look something like http://spreadsheets.google.com?...&key=123ABC

function initialize() {
  // Replace data source URL on next line with your data source URL
  var query = new google.visualization.Query("http://spreadsheets.google.com?...&key=123AB");
  query.send(handleQueryResponse);  // Send the query with a callback function
}

function handleQueryResponse(response) {
  // Called when the query response is returned
}

Processing the Query Response

The response handler function is called when the data source query returns. The parameter to the response handler function is of type google.visualization.QueryResponse. A query can fail, or run successfully. If the query was successful, the query response contains a data table (class google.visualization.DataTable). If the query failed, the query response contains information on the error, and no data table.

Typically, a response handler does the following:

  1. Checks if the query failed or ran successfully, and issues an error message when needed.
  2. Iterates on the returned data table, and creates some visualization of the data.


function handleQueryResponse(response) {

  if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
  }

  var data = response.getDataTable();
  var html = [];
  html.push('<table border="1">');

  // Header row
  html.push('<tr><th>Seq</th>');
  for (var col = 0; col < data.getNumberOfColumns(); col++) {
    html.push('<th>' + escapeHtml(data.getColumnLabel(col)) + '</th>');
  }
  html.push('</tr>');

  for (var row = 0; row < data.getNumberOfRows(); row++) {
    html.push('<tr><td align="right">' + (row + 1) + '</td>');
    for (var col = 0; col < data.getNumberOfColumns(); col++) {
      html.push(data.getColumnType(col) == 'number' ? '<td align="right">' : '<td>');
      html.push(escapeHtml(data.getFormattedValue(row, col)));
      html.push('</td>');
    }
    html.push('</tr>');
  }
  html.push('</table>');

  document.getElementById('tablediv').innerHTML = html.join('');
}

Creating Visualization Gadgets

For gadget developers there are additional gadget extensions that handles common visualization operations within gadgets:

  1. Create a query from user preferences.
  2. Handle error messages.

Read the gadget extensions document or the google.visualization.GadgetHelper reference for more information on developing visualization gadgets.

Troubleshooting

If your code doesn't seem to be working, here are some approaches that might help you solve your problems:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console, the Venkman Debugger, or the Firebug add-on. In IE, you can use the Microsoft Script Debugger.
  • Search the Google Visualization API discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.