Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to work with dynamic data and google charts?

For example we have this line chart at Google Code API

there is a defined set of data which this chart reflects, however i want to create the chart using my own data from php/mysql scripting.

Here is the code provided by google to embed into html page..

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['imagelinechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        // Create and populate the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.addRows(3);
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);

        // Create and draw the visualization.
        new google.visualization.ImageLineChart(document.getElementById('visualization')).
            draw(data, null);  
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 300px; height: 300px;"></div>
  </body>
</html>

The option i have in my mind is to keep the following piece of code in a loop and generate the data. Does someone have something easy and efficient way to do this?

data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.addRows(3);
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);
like image 837
Django Anonymous Avatar asked Apr 02 '12 06:04

Django Anonymous


1 Answers

Your question touches on something that's frustrated me a lot: Google's API documentation isn't great! In particular, for Charts API, in basically all of their examples, the data for their chart is hard coded in the page, and, in real life, you'll basically always be rendering data stored in a DB and transmitted to the browser.

1) You need some code on the server (I use PHP) that queries the database, "prints" and transmits the JSON/complex data structure which is an object where the properties are arrays that contain additional objects with properties and values in the exact format that Google's Chart JavaScript expects to receive it in the browser. I did it like this:

$sql = "SELECT year,d_pop FROM metrics WHERE year IN ('1940','1950','1960','1970','1980')";

$sth = mysql_query($sql, $conn) or die(mysql_error());

//start the json data in the format Google Chart js/API expects to recieve it
$JSONdata = "{
           \"cols\": [
               {\"label\":\"Year\",\"type\":\"string\"},
               {\"label\":\"Detroit Population\",\"type\":\"number\"}
             ],
        \"rows\": [";

//loop through the db query result set and put into the chart cell values
while($r = mysql_fetch_assoc($sth)) {
   $JSONdata .= "{\"c\":[{\"v\": " . $r['year'] . "}, {\"v\": " . $r['d_pop']  ."}]},";

}    

//end the json data/object literal with the correct syntax
$JSONdata .= "]}";

echo $JSONdata;

2) You need to receive that JSON object in your JavaScript on your page and pass it to Google's Chart JS. I brought in JQuery and then used it's AJAX method like this:

function drawChart() {
    var jsonData = $.ajax({
        url: "index_db.php",
        dataType:"json",
        async: false
    }).responseText;

    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable(jsonData);

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, {vAxis: {minValue: 0}});
}

My code snippets focus on the key parts of querying the mySQL DB, generating the JSON object Google Charts API needs, and receiving it with JQuery and AJAX. Hope this illuminates!

like image 64
Andrew Koper Avatar answered Sep 22 '22 13:09

Andrew Koper