Google Pie Chart : Uncaught Error: Container is not defined

Sébastien picture Sébastien · Apr 20, 2015 · Viewed 10.8k times · Source

I'm trying to display multiple google pie charts on the same page.

I get an Uncaught Error: Container is not defined error when doing so. How can I resolve this ?

My code :

function drawChart()
{
        var completeness = $(this).attr('data-completeness');

        var data = google.visualization.arrayToDataTable([
            ['Nom',    'Valeur'],
            ["Profil rempli à ", completeness],
            ['Manque', 100 - completeness]
        ]);

        var options = {
              ...
        };

        var chart = new google.visualization.PieChart(this);
        chart.draw(data, options);
}

$(function(){
    $('.piechart').each(function(){
        google.load('visualization', '1', {callback : drawChart, 'packages':['corechart']})
    });

});

Alternatively, if I iterate in the drawchart function, the output of the piechart gets really weird, it's not an arc anymore but about 5% of an arc (which does not happen if I do not set the completeness dynamically) :

function drawChart(elem)
{
    $(elem).each(function(){
        {#var completeness = {{ completeness }};#}
        var completeness = $(this).attr('data-completeness');

        console.log(completeness);

        var data = google.visualization.arrayToDataTable([
            ['Nom',    'Valeur'],
            ["Profil rempli à ", completeness],
            ['Manque', 100 - completeness]
        ]);

        var options = {
            backgroundColor: { fill:'transparent'},
            pieSliceBorderColor : 'transparent',
            pieHole: 0.8,
            legend: {position: 'top'},
            width: 220,
            height: 220,
            tooltip: {trigger: 'none'},
            pieStartAngle: -90,
            pieSliceTextStyle :{fontsize : 16, color: 'transparent'},
            slices: {
                0: { color: '#09b4ff'},
                1: { color: '#444'}
            },
            chartArea : {width: '90%', height: '90%'}
        };

        var chart = new google.visualization.PieChart(this);
        chart.draw(data, options);
    });
}

$(function(){
    google.load('visualization', '1', {callback : function(){drawChart('.piechart');}, 'packages':['corechart']})
});

Answer

Anto king picture Anto king · Apr 20, 2015

You have to use the document get element id and post like below

var chart = new google.visualization.PieChart(document.getElementById('container'))

Make sure you have the same id (container) html div tag, otherwise this will lead error