Insert Links into Google Charts api data?
Asked Answered
A

6

12

I have been playing around with Google charts quite a bit over in the google charts play ground here:

Link

The code I have been playing with is this:

function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Austria'],
    ['2003',  1336060],
    ['2004',  1538156],
    ['2005',  1576579],
    ['2006',  1600652],
    ['2007',  1968113],
    ['2008',  1901067]
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,
           {title:"Yearly Coffee Consumption by Country",
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Cups"}}
      );
}

and that gives me a nice chart that looks like this:

enter image description here

I am trying to have this chart fit the needs of my website, and to do this, I need to make the bar names on the left links to another page. So for example 2003 would be a link that the user can click ans so would 2004 etc.

I tried to do something like this:

function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Year', 'Austria'],
    ['<a href="url">Link text</a>',  1336060],
    ['2004',  1538156],
    ['2005',  1576579],
    ['2006',  1600652],
    ['2007',  1968113],
    ['2008',  1901067]
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,
           {title:"Yearly Coffee Consumption by Country",
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Cups"}}
      );
}

But I could only hope for it to be that easy and it wasn't. Does anyone know if this is at all possible?

Aggy answered 3/10, 2012 at 4:11 Comment(0)
L
9

This is non-trivial because the output you are seeing is SVG, not HTML. Those labels in your example ("2004", "2005", etc) are embedded inside SVG text nodes, so inserting raw HTML markup inside them will not be rendered as HTML.

The workaround is to scan for the text nodes containing the target values (again, "2004", "2005" etc) and replace them with ForeignObject elements. ForeignObject elements can contain regular HTML. These then need to be positioned more-or-less where the original SVG text nodes had been.

Here is a sample snippet illustrating all this. It is tuned to your specific example, so when you switch to rendering whatever your real data is, you will want to modify and generalize this snippet accordingly.

// Note: You will probably need to tweak these deltas
// for your labels to position nicely.
var xDelta = 35;
var yDelta = 13;
var years = ['2003','2004','2005','2006','2007','2008'];
$('text').each(function(i, el) {
  if (years.indexOf(el.textContent) != -1) {
    var g = el.parentNode;
    var x = el.getAttribute('x');
    var y = el.getAttribute('y');
    var width = el.getAttribute('width') || 50;
    var height = el.getAttribute('height') || 15;

    // A "ForeignObject" tag is how you can inject HTML into an SVG document.
    var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject")
    fo.setAttribute('x', x - xDelta);
    fo.setAttribute('y', y - yDelta);
    fo.setAttribute('height', height);
    fo.setAttribute('width', width);
    var body = document.createElementNS("http://www.w3.org/1999/xhtml", "BODY");
    var a = document.createElement("A");
    a.href = "http://yahoo.com";
    a.setAttribute("style", "color:blue;");
    a.innerHTML = el.textContent;
    body.appendChild(a);
    fo.appendChild(body);

    // Remove the original SVG text and replace it with the HTML.
    g.removeChild(el);
    g.appendChild(fo);
  }
});

Minor note, there is a bit of jQuery in there for convenience but you can replace $('text') with document.getElementsByTagName("svg")[0].getElementsByTagName("text").

Lemma answered 3/10, 2012 at 6:24 Comment(1)
Are there any charts api that I could do this easier with?Aggy
B
15

Manzoid's answer is good, but "some assembly is still required" as it just displays an alert box rather than following the link. Here is a more complete answer BUT it makes the bars clickable rather than the labels. I create a DataTable that includes the links then create a DataView from that to select the columns I want to display. Then when the select event occurs, I just retrieve the link from the original DataTable.

<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 data = google.visualization.arrayToDataTable([
          ['Year', 'link', 'Austria'],
          ['2003', 'http://en.wikipedia.org/wiki/2003',  1336060],
          ['2004', 'http://en.wikipedia.org/wiki/2004', 1538156],
          ['2005', 'http://en.wikipedia.org/wiki/2005', 1576579],
          ['2006', 'http://en.wikipedia.org/wiki/2006', 1600652],
          ['2007', 'http://en.wikipedia.org/wiki/2007', 1968113],
          ['2008', 'http://en.wikipedia.org/wiki/2008', 1901067]             
        ]);
       var view = new google.visualization.DataView(data);
       view.setColumns([0, 2]);

       var options = {title:"Yearly Coffee Consumption by Country",
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Cups"}};

       var chart = new google.visualization.BarChart( 
           document.getElementById('chart_div'));
       chart.draw(view, options);

       var selectHandler = function(e) {
          window.location = data.getValue(chart.getSelection()[0]['row'], 1 );
       }

       google.visualization.events.addListener(chart, 'select', selectHandler);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 900px;"></div>
  </body>
</html>
Bulletproof answered 6/2, 2013 at 11:59 Comment(0)
L
9

This is non-trivial because the output you are seeing is SVG, not HTML. Those labels in your example ("2004", "2005", etc) are embedded inside SVG text nodes, so inserting raw HTML markup inside them will not be rendered as HTML.

The workaround is to scan for the text nodes containing the target values (again, "2004", "2005" etc) and replace them with ForeignObject elements. ForeignObject elements can contain regular HTML. These then need to be positioned more-or-less where the original SVG text nodes had been.

Here is a sample snippet illustrating all this. It is tuned to your specific example, so when you switch to rendering whatever your real data is, you will want to modify and generalize this snippet accordingly.

// Note: You will probably need to tweak these deltas
// for your labels to position nicely.
var xDelta = 35;
var yDelta = 13;
var years = ['2003','2004','2005','2006','2007','2008'];
$('text').each(function(i, el) {
  if (years.indexOf(el.textContent) != -1) {
    var g = el.parentNode;
    var x = el.getAttribute('x');
    var y = el.getAttribute('y');
    var width = el.getAttribute('width') || 50;
    var height = el.getAttribute('height') || 15;

    // A "ForeignObject" tag is how you can inject HTML into an SVG document.
    var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject")
    fo.setAttribute('x', x - xDelta);
    fo.setAttribute('y', y - yDelta);
    fo.setAttribute('height', height);
    fo.setAttribute('width', width);
    var body = document.createElementNS("http://www.w3.org/1999/xhtml", "BODY");
    var a = document.createElement("A");
    a.href = "http://yahoo.com";
    a.setAttribute("style", "color:blue;");
    a.innerHTML = el.textContent;
    body.appendChild(a);
    fo.appendChild(body);

    // Remove the original SVG text and replace it with the HTML.
    g.removeChild(el);
    g.appendChild(fo);
  }
});

Minor note, there is a bit of jQuery in there for convenience but you can replace $('text') with document.getElementsByTagName("svg")[0].getElementsByTagName("text").

Lemma answered 3/10, 2012 at 6:24 Comment(1)
Are there any charts api that I could do this easier with?Aggy
L
6

Since the SVG-embedding route is (understandably) too hairy for you to want to muck with, let's try a completely different approach. Assuming that you have the flexibility to alter your functional specification a bit, such that the bars are clickable, not the labels, then here's a much simpler solution that will work.

Look for the alert in this snippet, that's the part that you will customize to do the redirect.

function drawVisualization() {
  // Create and populate the data table.
  var rawData = [
    ['Year', 'Austria'],
    ['2003',  1336060],
    ['2004',  1538156],
    ['2005',  1576579],
    ['2006',  1600652],
    ['2007',  1968113],
    ['2008',  1901067]
  ];
  var data = google.visualization.arrayToDataTable(rawData);

  // Create and draw the visualization.
  var chart = new google.visualization.BarChart(document.getElementById('visualization'));
  chart.draw(data,
           {title:"Yearly Coffee Consumption by Country",
            width:600, height:400,
            vAxis: {title: "Year"},
            hAxis: {title: "Cups"}}
      );
  var handler = function(e) {
    var sel = chart.getSelection();
    sel = sel[0];
    if (sel && sel['row'] && sel['column']) {
      var year = rawData[sel['row'] + 1][0];
      alert(year); // This where you'd construct the URL for this row, and redirect to it.
    }
  }
  google.visualization.events.addListener(chart, 'select', handler);
}
Lemma answered 3/10, 2012 at 16:50 Comment(0)
S
1

I apparently don't have enough reputation points to comment directly to a previous reply, so my apologies for doing so as a new post. manzoid's suggestion is great but has one issue I found, and it looks like Mark Butler might have run into the same problem (or unknowingly sidestepped it).

if (sel && sel['row'] && sel['column']) {

That line keeps the first data point from being clickable. I used it on a Jan-Dec bar chart, and only Feb-Dec were clickable. Removing sel['row'] from the condition allows Jan to work. I don't know that the if() condition is really even necessary, though.

Sodality answered 6/2, 2013 at 17:10 Comment(0)
C
1

Here's another solution that wraps each text tag for label with anchor tag.

  • no ForeignObject
  • clickable label
  • stylable by css (hover effect)

Here's a sample: https://jsfiddle.net/tokkonoPapa/h3eq9m9p/

/* find the value in array */
function inArray(val, arr) {
    var i, n = arr.length;
    val = val.replace('…', ''); // remove ellipsis
    for (i = 0; i < n; ++i) {
        if (i in arr && 0 === arr[i].label.indexOf(val)) {
            return i;
        }
    }
    return -1;
}

/* add a link to each label */
function addLink(data, id) {
    var n, p, info = [], ns = 'hxxp://www.w3.org/1999/xlink';

    // make an array for label and link.
    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) {
                /* wrap text tag with anchor tag */
                n = document.createElementNS('hxxp://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); // for speeding up
            }
        }
    });
}

function drawBasic() {
    var data = google.visualization.arrayToDataTable([
        ['City', '2010 Population', {role: 'link'}],
        ['New York City, NY', 8175000, 'hxxp://google.com/'],
        ['Los Angeles, CA',   3792000, 'hxxp://yahoo.com/' ],
        ['Chicago, IL',       2695000, 'hxxp://bing.com/'  ],
        ['Houston, TX',       2099000, 'hxxp://example.com'],
        ['Philadelphia, PA',  1526000, 'hxxp://example.com']
    ]);

    var options = {...};
    var chart = new google.visualization.BarChart(
        document.getElementById('chart_div')
    );

    chart.draw(data, options);

    addLink(data, 'chart_div');
}
Calculated answered 22/10, 2017 at 8:29 Comment(0)
L
0

You should use formatters.

If you replace value with HTML then sorting will not work properly.

Lindane answered 1/4, 2015 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.