Add Links into Google Charts - Javascript Google Chart

Javascript examples for Google Chart:Chart Configuration

Description

Add Links into Google Charts

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>An Example of a Google Bar Chart</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
      <style id="compiled-css" type="text/css">

svg a.city-name > text {
   fill: #0073aa;//from   w  w  w.j a v a2 s .  c  om
   text-decoration: underline;
}
svg a.city-name:hover > text {
   fill: #0096dd;
}


      </style> 
   </head> 
   <body> 
      <div id="chart_div"></div> 
      <script type="text/javascript">
google.charts.load('current', {
  packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawBasic);

function inArray(val, arr) {
  var i, n = arr.length;
  val = val.replace('?', ''); 
  for (i = 0; i < n; ++i) {
    if (i in arr && 0 === arr[i].label.indexOf(val)) {
      return i;
    }
  }
  return -1;
}

function addLink(data, id) {
  var n, p, info = [],
  ns = 'http://www.w3.org/1999/xlink';

  info = [];
  n = data.getNumberOfRows();
  for (i = 0; i < n; ++i) {
    info.push({
      label: data.getValue(i, 0),
      link: data.getValue(i, 2)
    });
  }
  $('#' + id).find('text').each(function(i, elm) {
    p = elm.parentNode;
    if ('g' === p.tagName.toLowerCase()) {
      i = inArray(elm.textContent, info);
      if (-1 !== i) {
        n = document.createElementNS('http://www.w3.org/2000/svg', 'a');
        n.setAttributeNS(ns, 'xlink:href', info[i].link);
        n.setAttributeNS(ns, 'title', info[i].label);
        n.setAttribute('target', '_blank');
        n.setAttribute('class', 'city-name');
        n.appendChild(p.removeChild(elm));
        p.appendChild(n);
        info.splice(i, 1); 
      }
    }
  });
}
function drawBasic() {
  var data = google.visualization.arrayToDataTable([
    ['City', '2010 Population', {
      role: 'link'
    }],
    ['New York City, NY', 8175000, 'http://google.com/'],
    ['Los Angeles, CA', 3792000, 'http://yahoo.com/'],
    ['Chicago, IL', 2695000, 'http://bing.com/'],
    ['Houston, TX', 2099000, 'http://example.com'],
    ['Philadelphia, PA', 1526000, 'http://example.com']
  ]);
  var options = {
    title: 'Population of Largest U.S. Cities',
    chartArea: {
      width: '50%'
    },
    hAxis: {
      title: 'Total Population',
      minValue: 0
    },
    vAxis: {
      title: 'City'
    }
  };
  var chart = new google.visualization.BarChart(
    document.getElementById('chart_div')
  );
  chart.draw(data, options);
  addLink(data, 'chart_div');
}

      </script>  
   </body>
</html>

Related Tutorials