Search code examples
phpmysqldynamic-datagoogle-visualization

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);

Solution

  • You can pass data as json instead making loop and passing with data.setCell()

    At php side make your data json format. Using json_encode(). And on Api use this method to pass data. Check this link for more information

    http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_toJSON