javascriptchartsgoogle-visualizationpie-chartgoogle-pie-chart

Add JavaScript links to pie slices of google visualizations pie chart


I'm working on a google visualizations pie chart and want each individual slice to link to a different page. I know there's another question already very similar to this, but I don't understand the answer. I've worked a bit with HTML and CSS but this is the first thing I've done in JavaScript and I'm definitely lost. I want my user to be able to click on a slice of the chart and then be taken to a new page. The page needs to be different for each slice of the chart if possible. Thank you! Here's my code:

<html>
  <head>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
            ['Field', 'Number of Proposals'],
            ['Sustainability', 242],
            ['Education', 699],
            ['Information Technology', 240],
            ['Health & Wellness', 247],
            ['Community Development', 353],
            ['Public Policy', 138],
            ['Equity', 276],
            ['Food & Water', 131],
            ['Energy', 84],
            ['Security (Cyber & Other)', 56],
        ]);

        var options = {'width': 1200,
                       'height': 700,
            colors: ['#8C1D40', '#FFC627', '#6F6F6F', '#935669', '#FFDA74', '#919191', '#96757F', '#FEE9B0', '#BBBBBB', '#DEDEDE']
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
        google.visualization.events.addListener (chart, 'select', function(){
            var selection = chart.getSelection();
    console.log(selection);
        });
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Solution

  • first, chart events should be added before the chart is drawn.

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    
    google.visualization.events.addListener(chart, 'select', function() {
      ...
    });
    
    chart.draw(data, options);
    

    next, the 'select' event fires both when a slice is selected, clicked.
    and un-selected when clicked again.
    so we must check the length of the selection,
    before trying to access the contents of the selection.

      var selection = chart.getSelection();
      if (selection.length > 0) {  // <-- check length of the selection
      }
    

    finally, we need a way to assign the page url to the slice.
    here, json format is used to assign a data table property (p:) to the slice label.

    [{v: 'Sustainability', p: {url: 'http://www.google.com'}}, 242],
    [{v: 'Education', p: {url: 'http://www.bing.com'}}, 699],
    [{v: 'Information Technology', p: {url: 'http://www.yahoo.com'}}, 699],
    

    then in the select event, we can get the property from the selection and open the page.

        var url = data.getProperty(selection[0].row, 0, 'url');
        window.open(url, '_blank');  // <-- remove '_blank' to open the page in the same window
    

    see following working snippet...
    note: window.open does not work from here, within the snippet,
    but it should work on your page.

    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {
    
      var data = google.visualization.arrayToDataTable([
        ['Field', 'Number of Proposals'],
        [{v: 'Sustainability', p: {url: 'http://www.google.com'}}, 242],
        [{v: 'Education', p: {url: 'http://www.bing.com'}}, 699],
        [{v: 'Information Technology', p: {url: 'http://www.yahoo.com'}}, 699],
      ]);
    
      var options = {'width': 1200,
        height: 700,
        colors: ['#8C1D40', '#FFC627', '#6F6F6F', '#935669', '#FFDA74', '#919191', '#96757F', '#FEE9B0', '#BBBBBB', '#DEDEDE']
      };
    
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    
      google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length > 0) {
          var url = data.getProperty(selection[0].row, 0, 'url');
          console.log(url);
          window.open(url, '_blank');
        }
      });
    
      chart.draw(data, options);
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="piechart"></div>