views:

759

answers:

1

I have a Google Chart (using the Google Visualization API, not Google Charts API) that populates on page load. After which, the user can select options from multiple drop-down menu's. I would like the user to be able to update the Google Chart based on their selections.

I've already created the PHP code to grab the new data via MySQL - after the user selects the various options.

Question: Should I need to replace the current graph? or should I create a JavaScript function to update the graph?

Here's my Google Chart JavaScript code:

google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Cluster');
  data.addColumn('number', 'Loans');
  data.addColumn('number', 'Lines');

/* create for loops to add as many columns as necessary */

var len = (encoded_cluster_name.length)-27; // encoded_line_volume.length;

  data.addRows(len);

for(i=0; i<len; i++) {

        var lines = (encoded_line_volume[i])/100000;
    var loans = (encoded_loan_volume[i])/100000;

data.setValue(i, 0, ' '+encoded_cluster_name[i]+' ');     /* x-axis */
data.setValue(i, 1, loans);    /* Y-axis category #1*/
data.setValue(i, 2, lines);    /* Y-axis category #2*/
}

/*********************************end of loops*****/

  var chart = new google.visualization.ColumnChart(
                document.getElementById('chart_div'));
  chart.draw(data, {
                    width: 600,
                    height: 300,
                    is3D: true,
                    title: 'Prospect Population',
                    legend: 'right'
                   });
}
+1  A: 

I would just update the data instead of replacing the chart. And request the chart get redrawn.

You can modify the playground example to test this out.
It looks like this:

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.
  var v=new google.visualization.ColumnChart(
          document.getElementById('visualization')
        );
  v.draw(data, null);
  // Pretend update data triggered and processed
  data.setCell(2, 1, 860);
  v.draw(data, null);
}
​
dlamblin
dlamblin,Thanks for answering my question. I owe ya one!brussels0828
brussels0828
You're welcome, and that playground link should have had the _ unencoded (as %5F) in the # portion of the URL. But posts get filtered for markdown. The link in this comment should work: http://code.google.com/apis/ajax/playground/?type=visualization#column_chart
dlamblin