You declare data0
and data1
in global scope and then create local scope variants of each in your handleQueryResponse
functions, so while data0
exists in handleQueryResponse1
, it is null
. Even if you used the global-scope variables, this wouldn't solve your problem, as it is entirely possible that query1
would return before query0
, and thus data0
would still be null.
Try this approach instead:
function drawChart() {
// create an array containing one false for each query
var ready = [false, false];
// create an array to hold the DataTables
var dataArray = [];
function handleQueryResponse(response, index) {
if (response.isError()) {
alert('Error in query ' + index + ': ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
ready[index] = true;
dataArray[index] = response.getDataTable();
var allReady = true;
// check if all the queries have returned
for (var i = 0; i < ready.length; i++) {
if (!ready[i]) {
allReady = false;
break;
}
}
// if all the queries have returned, draw the charts and tables
if (allReady) {
var data = new google.visualization.data.join(data[1], data[0], 'full', [0], [1], [1]);
var options = {
title: 'Electrolyser Data',
legend: {position: 'bottom'},
hAxis: {
title: 'Date',
titleTextStyle: {
color: 'red'
},
format: 'MMM d',
gridlines: {
count: 31
}
}
};
var tables = [];
tables[0] = new google.visualization.Table(document.getElementById('table_div0'));
tables[0].draw(dataArray[0]);
tables[1] = new google.visualization.Table(document.getElementById('table_div1'));
tables[1].draw(dataArray[1]);
tables[2] = new google.visualization.Table(document.getElementById('table_div2'));
tables[2].draw(data);
var charts = [];
charts[0] = new google.visualization.ColumnChart(document.getElementById('visualization0'));
charts[0].draw(dataArray[0], options);
charts[1] = new google.visualization.ColumnChart(document.getElementById('visualization1'));
charts[1].draw(dataArray[1], options);
}
}
var query0 = new google.visualization.Query('http://docs.google.com/spreadsheet/ccc?key=0AoTfmfAJUVoSdGRIVklheHdIS1ZCaHQ1MllvM19hUWc&sheet=MonthlyAvg-A');
var query1 = new google.visualization.Query('http://docs.google.com/spreadsheet/ccc?key=0AoTfmfAJUVoSdDhKOWRGRDNyeks1aF9jSFpHcmFfblE&sheet=MonthlyAvg-B');
query0.setQuery('select D,E limit 7');
query0.send(function (response) {
handleQueryResponse(response, 0);
});
query1.setQuery('SELECT D,E limit 7');
query1.send(function (response) {
handleQueryResponse(response, 1);
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});