Google Charts BarChart OnClick或OnSelect

时间:2014-01-13 18:14:25

标签: javascript mysql google-visualization

该代码会创建包含2列的Google Charts条形图。

<?php
$sth = mysql_query("select * from table");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
                array('label' => 'Stats', 'type' => 'string'),
                array('label' => 'Value', 'type' => 'number')
                );
$rows = array();
while($r = mysql_fetch_assoc($sth)) 
{
$temp = array();
$temp[] = array('v' => (string) $r['Stats']); 
$temp[] = array('v' => (int) $r['Value']); 
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>  
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
  var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
  var options = {
        legend: {position: 'none'},
    bar: {groupWidth: "85%"},
    colors:['#4A9218'],
    hAxis: {
                viewWindowMode: 'explicit',
                viewWindow: {
                             max: 400,
                             min: 0,
                             },
                 gridlines: {
                          count: 10,
                            }
                        }          
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" style="width:100%; height:200px"></div>

输出是简单的条形图,从MySQL提供数据。 有可能如何:

 1)To change Bar color when selected
 2)To change/populate seperate <div></div> content value regarding on selected Bar 

例如,您单击Bar,其值为“3”(动态)。条形图将颜色更改为红色。下面的DIV元素显示值“3”

1 个答案:

答案 0 :(得分:7)

是的,您可以通过添加'select'事件处理程序来获取DataTable中的数据,使用值更新div,通过'style'角色列设置栏的颜色在DataView中,使用视图重绘图表。这是一个例子:

google.visualization.events.addListener(chart, 'select', function () {
    var selection = chart.getSelection();
    if (selection.length) {
        var row = selection[0].row;
        document.querySelector('#myValueHolder').innerHTML = data.getValue(row, 1);

        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1, {
            type: 'string',
            role: 'style',
            calc: function (dt, i) {
                return (i == row) ? 'color: red' : null;
            }
        }]);

        chart.draw(view, options);
    }
});

在此处查看:http://jsfiddle.net/asgallant/kLL2s/