Javascript 在谷歌图表api数据中插入链接?

Javascript 在谷歌图表api数据中插入链接?,javascript,web,google-visualization,Javascript,Web,Google Visualization,我一直在谷歌图表的游戏场地上玩谷歌图表: 我一直在玩的代码是: function drawVisualization() { // Create and populate the data table. var data = google.visualization.arrayToDataTable([ ['Year', 'Austria'], ['2003', 1336060], ['2004', 1538156], ['2005', 15765

我一直在谷歌图表的游戏场地上玩谷歌图表:

我一直在玩的代码是:

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"}}
      );
}
这给了我一个很好的图表,看起来像这样:

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"}}
      );
}

我正试图让这个图表适合我的网站的需要,要做到这一点,我需要使左边的链接到另一个页面的酒吧名称。例如,2003年是一个链接,用户可以点击ans,2004年也是如此

我试着这样做:

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"}}
      );
}
函数drawVisualization(){
//创建并填充数据表。
var data=google.visualization.arrayToDataTable([
[“年”,“奥地利”],
['',  1336060],
['2004',  1538156],
['2005',  1576579],
['2006',  1600652],
['2007',  1968113],
['2008',  1901067]
]);
//创建并绘制可视化。
新的google.visualization.BarChart(document.getElementById('visualization'))。
绘制(数据、,
{标题:“各国每年咖啡消费量”,
宽度:600,高度:400,
vAxis:{标题:“年”},
哈克斯:{title:“Cups”}
);
}

但我只能希望事情能这么简单,但事实并非如此。有人知道这是否可能吗?

这很重要,因为您看到的输出是SVG,而不是HTML。示例中的标签(“2004”、“2005”等)嵌入在SVG文本节点中,因此在其中插入原始HTML标记将不会呈现为HTML

解决方法是扫描包含目标值的文本节点(同样是“2004”、“2005”等),并用元素替换它们<代码>外来对象元素可以包含常规HTML。然后需要或多或少地将它们放置在原始SVG文本节点所在的位置

下面是一个示例片段,说明了所有这些。它根据您的特定示例进行了调整,因此当您切换到渲染真实数据时,您将需要相应地修改和概括此代码段

// 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);
  }
});

小提示,为了方便起见,这里有一点jQuery,但是您可以用
文档来替换
$('text')
。getElementsByTagName(“svg”)[0]。getElementsByTagName(“text”)

,因为svg的嵌入路径(可以理解)太复杂,您不想弄乱,让我们尝试一种完全不同的方法。假设您可以灵活地稍微更改功能规范,使条形图可以单击,而不是标签,那么这里有一个简单得多的解决方案

在这段代码中查找
警报
,这是您将自定义以执行重定向的部分

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);
}

Manzoid的回答很好,但“仍然需要一些组件”,因为它只显示一个警报框,而不是按照链接进行操作。这里有一个更完整的答案,但它使工具栏可以点击,而不是标签。我创建一个包含链接的,然后从中创建一个来选择要显示的列。然后,当select事件发生时,我只是从原始数据表中检索链接

<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>

load(“可视化”、“1”、{packages:[“corechart”]});
setOnLoadCallback(drawChart);
函数绘图图(){
var data=google.visualization.arrayToDataTable([
[“年”、“链接”、“奥地利”],
['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=newgoogle.visualization.DataView(数据);
view.setColumns([0,2]);
var选项={title:“各国每年咖啡消费量”,
宽度:600,高度:400,
vAxis:{标题:“年”},
哈克斯:{头衔:“杯子”};
var chart=新的google.visualization.BarChart(
document.getElementById('chart_div');
图表绘制(视图、选项);
var selectHandler=函数(e){
window.location=data.getValue(chart.getSelection()[0]['row'],1);
}
google.visualization.events.addListener(图表'select',selectHandler);
}

我显然没有足够的声望点来直接评论之前的回复,所以作为一个新帖子,我很抱歉这么做。曼佐伊德的建议很好,但我发现了一个问题,马克·巴特勒似乎也遇到了同样的问题(或者在不知不觉中回避了这个问题)

该行使第一个数据点不可单击。我在一月到十二月的条形图上使用了它,只有二月到十二月是可点击的。从条件中删除sel['row']允许Jan工作。不过,我甚至不知道if()条件是否真的是必要的。

您应该使用


如果用HTML替换值,则排序将无法正常工作。

下面是另一个解决方案,它将标签的每个文本标记包装为锚标记

  • 无<代码>外来物体
  • 可点击标签
  • 可通过css设置样式(悬停效果)
以下是一个示例:

/*在数组中查找值*/
函数INARAY(val、arr){
var i,n=阵列长度;
val=val.replace(“…”,“);//删除省略号
对于(i=0;i/* 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');
}