Pages

Thursday, December 1, 2011

Google visualization Tips & Tricks

Google visualization is great for adding interactive charts to a web application. I used it extensively in one of my projects and I ended up using a couple of tricks to improve its performance and appearance.

Show a loading animation

Showing a loading animation while the visualization library is loading, is incredibly easy. All you have to do is insert a .gif image into each div that is a target for a chart. After the library has loaded and the draw method is called, it will automatically replace anything that was placed inside the target div with the chart.
<div id="chart_div">
    <img src="loading.gif">
</div>

Autoloading


The autoload feature in google javascript api is great for reducing loading time when you need a specific library, in this case, visualization. Instead of calling google.load after loading the js api you can specify which modules you need.
<script src="http://www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1","packages":["corechart", "table", "annotatedtimeline"]}]}"></script>

Lazy loading

At one point I had to load three visualization packages on one page to show a dashboard with many charts. As a result the size and loading time of the javascript library became considerably large. So I came up with a trick that does not actually reduce the loading time but it lets you load the modules sequentially so you can display some charts while the others are loading. The trick is to load only one package in the first autoload call. And when the callback method of the first request is called you can draw the charts of that packages and then call google.load to load the remaining packages. So instead of specifying all three packages like in the above example you should only specify one. And when the callback is called you can load the other packages lazily.
google.setOnLoadCallback(drawChart);
function drawCharts() {
    drawCoreCharts();
    google.load('visualization', '1.0', {'packages':['gauge'], 'callback': 'drawGauge'});
}