Google Visualization API – Implement event handler on data point

Here is an example on binding the select event handler on the data point.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var rawData = [
          ['Year', 'Sales', 'Expenses'],
          ['2004', 1000,    400],
          ['2005', 1170,    460],
          ['2006', 660,     1120],
          ['2007', 1030,    540]
        ];
        var data = google.visualization.arrayToDataTable(rawData);

        var options = {
          title: 'Company Performance'
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

        // Add the select event handler
        google.visualization.events.addListener(chart, 'select', function () {
          var sel = chart.getSelection();
          sel = sel[0];
          if (sel && sel['row'] && sel['column']) {
            var year = rawData[sel['row'] + 1][0];
            var salesValue = rawData[sel['row'] + 1][1];
            var expensesValue = rawData[sel['row'] + 1][2];
            console.log("year: " + year + ", sales: " + salesValue + ", expenses: " + expensesValue);
          }
        });
        
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Continue reading

About these ads