How to Add a Google Chart to a UX Component

Description

The Google visualization libraries offer an alternative to creating and displaying charts in a UX Component.

To add a Google Chart to your app, you need a DIV in your UX Component that can be used to display the chart. For example, the following code when added to a Static Text control creates a DIV called "mychart" that can be used to load a Google Chart:

<div id="mychart" style="width: 6in; height: 6in; border: solid 1px blue;">Chart goes here</div>

The following function creates an Area Chart that is then displayed in the "mychart" DIV:

function chart1 () {
    var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004', 1000, 400],
        ['2005', 1170, 460],
        ['2006', 660, 1120],
        ['2007', 1030, 540]
    ]);

    var options = {
        title: 'Company Performance',
        hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
        vAxis: {minValue: 0}
    };

    var chart = new google.visualization.AreaChart($('mychart'));
    chart.draw(data,options);
}
The Area Chart is part of the corechart Google Chart Library. To use the Area Chart, you will need to check the corechart option for the Google visualization libraries property of the UX Component.

The last step is to call the chart1() function to display the Area Chart. This can be done by adding JavaScript to the click event for a button to call the chart1() function. For example:

chart1();

Charts can be rendered on demand using buttons or dynamically using ajax callbacks, server-side events, or client-side events. For example, the afterGoogleVisualization client-side UX event fires after the Google Visualization library has loaded. Calling chart1() in this event will load the chart immediately after the Google Visualization API is loaded and ready.

To learn more about how to use Google Charts in your applications, watch the video below:

Using Google Charts as an Alternative to the Build-in Chart Controls

Download Component

It is no longer necessary to go to the Web Project Properties dialog to specify that the Google JSAPI library should be loaded. The Visualization libraries are now loaded automatically by the UX as needed.

See Also