Dynamic data with Google Charts

只谈情不闲聊 提交于 2019-12-23 23:02:43

问题


I require my Google chart to be drawn with dynamic data, so I'm storing it in a variable:

var rowData = "[ [{ v: 'Mike', f: 'Mike' }, '', 'The President'], [{ v: 'Jim', f: 'Jim Vice President' }, 'Mike', 'VP'], ['Alice', 'Mike', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ]";

I'm then passing this variable into Google's function:

    google.load('visualization', '1', { packages: ['orgchart'] });
    //google.setOnLoadCallback(drawChart);
    function drawChart(json) {
        data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');
        data.addRows([
            rowData
        ]);
        chart = new google.visualization.OrgChart(document.getElementById('orgChart'));
        chart.draw(data, { allowHtml: true });
        google.visualization.events.addListener(chart, 'select', selectHandler);
    }

However, this gives me an 'Every row given must be either null or an array.' error. If I remove the variable and pass the data in directly, it works fine:

    ...
    data.addRows(
        [ [{ v: 'Mike', f: 'Mike' }, '', 'The President'], [{ v: 'Jim', f: 'Jim Vice President' }, 'Mike', 'VP'], ['Alice', 'Mike', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ]
    );
    ...

Can anyone help tell me what's going on here? Thanks in advance.


回答1:


In your first example the data is a single string, in the second example your data is a JavaScript structure of arrays and individual strings / values.

Hard to recommend a best-practice without knowing where you're dynamic data is coming from, but you should be able to remove the outermost quotes like this and have it work:

var rowData = [ [{ v: 'Mike', f: 'Mike' }, '', 'The President'], [{ v: 'Jim', f: 'Jim Vice President' }, 'Mike', 'VP'], ['Alice', 'Mike', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ];



回答2:


By enclosing in double-quotes rowData becomes string while the API needs Array. Use it like this

var rowData = [ [{ v: 'Mike', f: 'Mike' }, '', 'The President'], [{ v: 'Jim', f: 'Jim Vice President' }, 'Mike', 'VP'], ['Alice', 'Mike', ''], ['Bob', 'Jim', 'Bob Sponge'], ['Carol', 'Bob', ''] ];


来源:https://stackoverflow.com/questions/9103951/dynamic-data-with-google-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!