简体   繁体   中英

Google Pie chart usage with Jquery inside a function?

I want to use google pie chart inside jquery and want the chart to be generated based on the condition.

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var options = {title: 'Sample Chart'};
function drawChart() {
    var data1 = new google.visualization.DataTable();
    data1.addColumn('string', 'col1');
    data1.addColumn('number', 'col2');
    data1.addRow(["sample", 12]);
    data1.addRow(["sample", 24]);
    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data1, options);
}

Jquery function,

$.each(result, function(index) {
    $("#tableContents").append("some html generation");
});

I want the data1 to be prepared during the loop of Jquery and draw at the end of the function. I see that if I takeout the data1 part of code (shown below) outside the function drawchart, I get

in console log,

Cannot read property 'DataTable' of undefined error

The data1 part of code I removed out of drawChart(),

var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);

Please help, thanks in advance.

You can parse the results into the DataTable like this:

function drawChart() {
    var data1 = new google.visualization.DataTable();
    data1.addColumn('string', 'col1');
    data1.addColumn('number', 'col2');

    $.each(result, function(index) {
        $("#tableContents").append("some html generation");
        // assumes results[index] has "col1Value" and "col2Value" properties
        data1.addRow([results[index].col1Value, results[index].col2Value]);
    });

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data1, options);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM