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>

 

Now if you click on the data point on the chart, the corresponding values are printed to the console.
google-visualization-api-implement-event-handler

Done =)

Reference: StackOverflow – Insert Links into Google Charts api data?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.