Insert Links into Google Charts api data?

后端 未结 6 1207
日久生厌
日久生厌 2020-12-10 13:08

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:

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 13:58

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

提交回复
热议问题