google.visualization.PieChart is not a constructor

Gaurav_0093 picture Gaurav_0093 · Mar 10, 2017 · Viewed 7.9k times · Source

I am using pie chart to show the data here is my code I have added the following script

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script type="text/javascript">
        google.charts.load('current', { 'packages': ['corechart', 'gauge'] });

and my function which is used to display chat:-

self.DrawServiceGraph = function (obj) {
                var dataArray = new Array();
                dataArray.push(['Services', 'Total']);
                var subCat = ko.utils.arrayFirst(self.SelectedServiceSubCategoryList(), function (o) { return o.Id === obj.Id; });
                if (subCat !== undefined) {
                    $.each(subCat.SSC_List(), function (index, item) {
                        var value = parseInt(item.Value());
                        dataArray.push([item.SSC_Name, value]);
                    });

                    var data = google.visualization.arrayToDataTable(dataArray);

                    var options = {
                        title: '', height: 230, width: 330,
                        chartArea: { left: 0, width: '100%' },
                        legend: { position: 'right', alignment: 'start', maxLines: 5, textStyle: { fontSize: 10 } }
                    };

                    var chart = new google.visualization.PieChart(document.getElementById('Services-chart' + obj.Id));
                    chart.draw(data, options);
                }
            }

Then i got the error from line:

google.visualization.Pie Chart is not a constructor and google.visualization.arrayToDataTable is not a constructor

What should be the possible solutions to avoid this errors?

Answer

WhiteHat picture WhiteHat · Mar 10, 2017

are you waiting for the load statement to finish?

use the callback to know when it is ok to begin drawing...

google.charts.load('current', {
  callback: function () {
    // begin drawing
  },
  packages: ['corechart', 'gauge']
});

-- or --

google.charts.load('current', {
  packages: ['corechart', 'gauge']
});
google.charts.setOnLoadCallback(function () {
  // begin drawing
});