Google Visualizations

Google's Visualization API allows developers to visualize data in meaningful ways on their web pages. Google, and its community members have created many interesting visualizations. A few are shown below:



An ever-increasing list of visualizations can be found in the Google Visualization Gallery. We’ve also shared a project on developer.force.com/codeshare that makes it dead simple for Force.com developers to utilize Google visualizations in their Visualforce pages. This article will discuss how to use the code found in that project.

Installation

The first thing that you'll need to do is install the Google Visualizations project from Code Share in to your Developer Edition org. The instructions for doing so are here.

Architecture

The diagram below illustrates the different components of a Visualforce page that utilizes a custom Google Visualization component. It’s important to notice that in order to embed a Google Visualization in a Visualforce page, you only need to provide the blue-colored portions of the diagram. Namely, a Visualforce page that will display the visualization and an Apex controller that will query the data for the visualization. The components themselves and their supporting classes are provided for you.



System Interactions

One of the interesting aspects of Google Visualizations is that they are rendered client-side in the user’s browser. This means that none of your sensitive data is ever sent outside of the Force.com platform.



The diagram above shows that when a user requests a Visualforce page containing a Google Visualization component, the Visualforce page will call a method from the page’s controller. This method will return a dataset in the form of a JSON string. This page will then be returned to the user’s browser. The page will then instruct the users’s browser to download the appropriate visualization JavaScript from Google’s servers. Once downloaded, the user’s browser will use the visualization JavaScript to process and render the JSON-formatted data.

Sample Page

Here’s a sample Visualforce page with a Timeline visualization on it:



Generated JSON

The data behind the above timeline is a 2-dimensional table:

Date Cosmo G. Spacely Account Name Opportunity Amount
7/1/2008 1 Robot Maid Co. $500,000
7/7/2008 2 Flying Cars, Inc. $300,000

In JSON -format, that looks like:

{cols: [
	  {id: "col1", label: "Date", type: "date"},
	  {id: "col2", label: "Cosmo G. Spacely", type: "number"},
  	  {id: "col3", label: "Account Name", type: "string"},
	  {id: "col4", label: "Opportunity Amount", type: "string"}
       ], 
 rows: [
        {c:[{v: new Date(2008, 7, 1, 0, 0, 0), f: "7/1/2008"}, 
            {v: 1.0},
            {v: "Robot Maid Co."}, 
            {v: 500000.0}]},
        {c:[{v: new Date(2008, 7, 7, 0, 0, 0), f: "7/7/2008"}, 
            {v: 2.0},
            {v: "Flying Cars, Inc."}, 
            {v: 300000.0}]}, 
	 … 
       ]
}

Generated HTML

If you're curious, the HTML generated by the Visualforce page can be viewed here.

Google Visualization JavaScript

And the (obfuscated) visualization JavaScript sent by Google can be viewed here.

Visualforce Page

Let’s dig a little deeper to understand how the Visualforce page, the Google Visualization component and the Controller generate the above HTML.

<apex:page controller="SalesController" showheader="false">
<html>
   <body>

      Number of Sprockets Sold By Rep<br/>

	<c:TimeLine jsondata="{!SalesActivity}" 
	            width="900px" height="300px" 
	            zoomStartTime="new Date(2008, 07, 01)" 
	            zoomEndTime="new Date(2008, 09, 30)" 
	            displayZoomButtons="false"
	            colors="'#C2CD23'" />

   </body>
</html>
</apex:page>

As you can see, there’s not too much going on in the VF page, just a few of the component parameters being set. The most interesting part of the page is the call to the getSalesActivity() method of the controller.

Apex Controller

The getSalesActivity() method in the controller example below does five things:

  • Instantiates a GoogleViz object
  • Queries the Opportunity table for all of the current User’s Opportunities.
  • Creates a row of data for each Opportunity.
  • Calls the toJsonString() method from the GoogleViz class to return the dataset as a JSON-formatted string.


public class SalesController {

    public String getSalesActivity(){
        GoogleViz gv = new GoogleViz();
                
        gv.cols = new list<GoogleViz.col> { 
            new GoogleViz.Col('col1','Date','date'),
            new GoogleViz.Col('col2', UserInfo.getFirstName() + ' ' + 
                                      UserInfo.getLastName(), 'number'),
            new GoogleViz.Col('col3','Account Name','string'),
            new GoogleViz.Col('col4','Opportunity Amount','string')
        };
                
        Integer numOpportunities = 1;
        
        for( Opportunity o : [SELECT Id, Name, Amount, CloseDate, Account.Name, Owner.Name
                              FROM Opportunity
                              WHERE IsWon = true AND OwnerId = :UserInfo.getUserId()
                              ORDER BY CloseDate ASC]){

            GoogleViz.row r = new GoogleViz.row();
            r.cells.add ( new GoogleViz.cell(o.CloseDate) ); // Date column
            r.cells.add ( new GoogleViz.cell(numOpportunities) ); // Quantity column
            r.cells.add ( new GoogleViz.cell(o.Account.Name) ); // Annotation Title column
            r.cells.add ( new GoogleViz.cell(o.Amount) ); // Annotation Text column

            gv.addRow( r );

            numOpportunities++;
        }

        return gv.toJsonString();
    }  
}

You’ll notice that there isn’t any JSON-specific code in the controller though. This is because the JSONObject.cls Apex class included in the project takes care of the formatting for you. Your controller just has to extract the relevant data and place it in the GoogleViz object.

And that's it! With just a very small amount of Visualforce and Apex code, it is now possible to embed valuable and insightful visualizations inside your Visualforce pages.

Additional Visualizations

If you’re feeling adventurous, you can take a look at the code for the Visualforce components. You'll see that the complexity level is rather low and that it would be quite easy to add additional components to the project – which you can contribute back to the community via the Code Share project.

Force.com as a Google Visualization Data Source

In addition to being able to embed embed Google Visualizations in your Force.com applications, you can also expose some of your Force.com data in a way that is compliant with the Google Visualization API. This lets your carefully crafted public data drive Google Gadgets and Google Visualizations on your own website - or on any other website that supports embedding the gadgets and visualizations. Learn more about exposing data on Force.com to support the Google Visualization API.

Updating Your Google Visualizations Project

This project is periodically updated with code improvements and new components. To update your Google Visualization project in the future, follow the instructions described here.

Related Content

About the Author

Jesse Lorenz is a Technical Evangelist at salesforce.com, helping independent software vendors, product teams and other partners to architect and build innovative applications on Force.com.