fst104 fst104 - 8 days ago 10
Javascript Question

TypeError: google.visualization.DataTable is not a constructor

On my web page I have a google map, as well as three charts. When the page loads the map is fine, but the charts either don't load or only one or two do. Keep getting the error TypeError: google.visualization.DataTable is not a constructor.

function load() {
//map object
var MY_MAP = new google.maps.Map(document.getElementById("map"), {
center: {lat: 54.870902, lng: -6.300565},
zoom: 14
});
//call to get and process data
downloadUrl("Map.php", processXML);
}

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawAltitudeChart());
google.setOnLoadCallback(drawDisplacementChart());
google.setOnLoadCallback(drawDistanceChart());



function drawAltitudeChart(){

//console.log('hello');
var graph = [];
downloadUrl("Map.php", function (data){
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var dataTable = new google.visualization.DataTable();
var options = {title:'Altitude (m above sea level)',
curveType:'function',
legend:{position:'bottom'},
is3d:true
};
var chart;

for(var i = 0; i<markers.length; i++){
graph[i] = ['', parseInt(markers[i].getAttribute("alt"))];
}

dataTable.addColumn('string', 'id');
dataTable.addColumn('number', 'Altitude');
dataTable.addRows(graph);


chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(dataTable, options);

});
}

Answer

I don't think you can add more than one callback like that.

Also, you can define the callback in the load method, like so...

google.load('visualization', '1.0', {'packages':['corechart'], 'callback': drawCharts});

function drawCharts() {
  drawAltitudeChart();
  drawDisplacementChart();
  drawDistanceChart();
}

EDIT

the above load statement is for the older library...

<script src="http://www.google.com/jsapi"></script>

according to the release notes...

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

using the new library...

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

changes the load statement to...

google.charts.load('current', {'packages': ['corechart'], 'callback': drawCharts});
Comments