如何在Google Charts中获取有关所选栏的信息?

时间:2017-09-14 18:21:42

标签: charts google-visualization

我有一张通过Google Charts API呈现的图表。当用户点击栏时,如何获取有关所选栏的数据。我理解它到了#34; getSelection"调用输出选择信息。当我点击一个酒吧时,我得到了这个。 enter image description here

我的代码是



      <div class="row">
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
         
      var data = google.visualization.arrayToDataTable([
      ['Salesman', 'Visit'],
      
      //Some PHP Code
      
      ]);

        var options = {
          chart: {
            title: '',
            subtitle: '',
          }
        };

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
        chart.draw(data, google.charts.Bar.convertOptions(options));
        google.visualization.events.addListener(chart, 'select', selectHandler);
      }

function selectHandler() {

    var selectedItem = chart.getSelection()[0];
if (selectedItem) {
    var selectedValue = data.getValue(selectedItem.row, 0);
    console.log('The user selected ' + selectedValue);
}

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

selectHandler需要在与chart

相同的范围内定义

在这种情况下,只需将selectHandler移至drawChart

即可

请参阅以下工作代码段...

&#13;
&#13;
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Salesman', 'Visit'],
    ['A', 2],
    ['B', 3]
  ]);

  var options = {
    chart: {
      title: '',
      subtitle: '',
    }
  };

  var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
  chart.draw(data, google.charts.Bar.convertOptions(options));
  google.visualization.events.addListener(chart, 'select', selectHandler);

  function selectHandler() {
    var selectedItem = chart.getSelection()[0];
    if (selectedItem) {
      var selectedValue = data.getValue(selectedItem.row, 0);
      console.log('The user selected ' + selectedValue);
    }
  }
}
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_material"></div>
&#13;
&#13;
&#13;