Search code examples
javascripthtmldata-visualizationgoogle-api-javascript-client

Uncaught (in promise) Error: Data for arrayToDataTable is not an array in visualizing data using https://www.google.com/jsapi


I am trying to visualize data from a javascript file as shown below.

data = [ ['Year','China','India'],
['C1960',1.83286768126466,1.96098348563911],
['C1961',-1.01552778731319,1.99843774000741],
['C1962',0.820455548748518,2.03190545392019],
.
.
.
['C1963',2.45764740395145,2.0569116837358],
['C2017',0.559121331017265,1.06259739387194],
['C2018',0.455899678672578,1.03732336037888],
['C2019',0,0]
];

The html code I am using is as below.

<html>
  <head>
    <script type="text/javascript" src="data.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable( data );

        var options = {
          title: 'World Bank Data Visualization',
          chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
        };

        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 1300px; height: 600px;"></div>
  </body>
</html>

I am getting the error as

Uncaught (in promise) Error: Data for arrayToDataTable is not an array.
    at Object.gvjs_ll [as arrayToDataTable] (jsapi_compiled_default_module.js:188)
    at drawChart (data.htm:9)

Can anyone help me please? When I am loading another javascript file like this, it perfectly works. I don't know what is wrong with my code.


Solution

  • In your html, you have a variable named data. Due to this, the variable data from data.js is shadowed. More detail about Variable Shadowing here.

    To make your code work, change that variable name to something else.

    Something like:

    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var dataVis = google.visualization.arrayToDataTable( data );
    
      var options = {
           title: 'World Bank Data Visualization',
           chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
      };
    
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(dataVis, options);
    }