所以我正在用HTML构建一个基本的仪表板,并使用谷歌的可视化API来实现。我需要创建许多图形和下面的代码工作得很好。除了一个问题:数据本身似乎是随机归于图表的。每当我重新加载页面时,图形就会切换显示的数据。
我试图通过与其他数组一起创建dataArray来解决这个问题,但这并没有解决问题-必须有某种方法将数据直接属性到查询中的图表中。谢谢!
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {packages: ['corechart']});
// Set a callback to run when the Google Visualization API is loaded
google.charts.setOnLoadCallback(function() {
drawChart('chart1', 0, 'SELECT A, B, C, D, E, G OFFSET 1', 'Sheet1',
{ title: 'Chart 1'}
)
drawChart('chart2', 1, 'SELECT A, I OFFSET 1', 'Sheet1',
{ title: 'Chart 2' }
)
});
var chartsArray = [];
var optionsArray = [];
var nextID = 0;
function drawChart(tag, id, sqlCommand, sheetName='Sheet1', options= {}, numHeaders=1) {
chartsArray[id] = new google.visualization.LineChart(document.getElementById(tag));
optionsArray[id] = options;
var queryString = encodeURIComponent(sqlCommand);
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1L8jhM7FHOg86hZMIJB2L_032-JbGKzX4ht6r3mxvP0gA/gviz/tq?sheet=' + sheetName + '&headers=' + numHeaders.toString() + '&tq=' + queryString);
query.send(handleDataQueryResponse);
}
function handleDataQueryResponse(response, id) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
chartsArray[nextID].draw(data, optionsArray[nextID]);
nextID += 1;
}
<div id="chart1" class="chart"></div>
<div id="chart2" class="chart"></div>
更新:我已经解决了这个问题(目前,可怕的解决方案)通过调用setTimeout(),从而强制调用可视化API执行在我想要的顺序。
回调函数handleDataQueryResponse
是异步调用的,所以你不能保证一个会在另一个之前完成…
推荐这样的东西…
function drawChart(tag, id, sqlCommand, sheetName='Sheet1', options= {}, numHeaders=1) {
chartsArray[id] = new google.visualization.LineChart(document.getElementById(tag));
optionsArray[id] = options;
var queryString = encodeURIComponent(sqlCommand);
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1L8jhM7FHOg86hZMIJB2L_032-JbGKzX4ht6r3mxvP0gA/gviz/tq?sheet=' + sheetName + '&headers=' + numHeaders.toString() + '&tq=' + queryString);
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
chartsArray[id].draw(data, optionsArray[id]);
});
}