Search code examples
google-visualization

Google charts error:every row given must be either null or an array


I am working on a website that is intended to show some basic Google charts. The data comes from a text file that i retrieve through Ajax. It's got a x, y value and an annotation field. The data looks like this:

[[-0.8, -0.47, "100-005-10"],
[-0.7, -0.46, "100-005-9"],
[-0.6, -0.45, "100-005-8"],
[-0.5, -0.44, "100-005-7"]]

Here's my code:

    <script >


  var xmlhttp = new XMLHttpRequest();
  var array;
  xmlhttp.onreadystatechange = function() {

      array = this.responseText;    

  };
  xmlhttp.open("GET", "array.array", true);
  xmlhttp.send(); 


    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

        var data = google.visualization.arrayToDataTable($.parseJSON(array), true)

        data.addColumn('number', 'x');
        data.addColumn('number', 'y');
        data.addColumn({type: 'string', role: 'annotation'});

        data.addRow(array);


      var options = {
        legend: 'none',
        colors: ['#087037'],        
        selectionMode: 'single',       
        tooltip: {trigger: 'selection'},
        pointSize: 12,
        animation: {
          duration: 200,
          easing: 'inAndOut',
        }
      };

      var chart = new google.visualization.ScatterChart(document.getElementById('animatedshapes_div'));

      chart.draw(data, options);


    }
  </script>

When i run the code, i get this error message:

Error: If argument is given to addRow, it must be an array, or null

I just don't know how to transform the plain text from the ajax response to an array.


Solution

  • try using JSON.parse to convert the string to an actual array...

    data.addRows(JSON.parse(array));