我使用NodeJS和Socket.io从数据库中获取数据。我现在想用这些数据填写谷歌区域图表,但我有点失败。
数据以Objects
传输。每个Object
包含两个值(日期时间和值)。我将这些值附加到数组中,然后将它们存储在DataTable
:
google.load('visualization', '1', {
packages: ['corechart']
});
google.setOnLoadCallback(drawChart);
var socket = io();
getData();
function drawChart(dataArray) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'DateTime');
data.addColumn('number', 'Value');
for (var i = 0; i < dataArray.length; i += 2) {
console.log(dataArray[0]);
data.addRow([dataArray[i], dataArray[i + 1]]);
}
var chart = new google.visualization.AreaChart(document.getElementById('chart'));
chart.draw(data, {
title: "Data Visualization",
isStacked: true,
width: '50%',
height: '50%',
vAxis: {
title: 'Data v-Axis'
},
hAxis: {
title: 'Data h-Axis'
}
})
}
function getData() {
socket.emit('GET');
socket.on('serverSent', function (data) {
var processedData = processData(data);
drawChart(processedData);
})
}
function processData(data) {
var arr = new Array();
jQuery.each(data, function (index, object) {
arr.push(object['datetime'], parseInt(object['value']));
})
return arr;
}
如果我打电话给我的网站,我会看到图表,但没有任何值,错误消息“google.visualization.DataTable不是构造函数”。我做错了什么?
答案 0 :(得分:1)
问题是drawChart
被调用两次
来自google.setOnLoadCallback
和getData
。
如果在getData
之前调用google.setOnLoadCallback
,则
然后google.visualization.DataTable
将无法识别。
此外,建议使用loader.js
与jsapi
有关详细信息,请参阅Load the Libraries
因此,请尝试以下方法......
替换...
<script src="https://www.google.com/jsapi"></script>
使用...
<script src="https://www.gstatic.com/charts/loader.js"></script>
尝试类似......
google.charts.load('current', {
callback: init,
packages: ['corechart']
});
function init() {
var socket = io();
socket.emit('GET');
socket.on('serverSent', function (data) {
var processedData = processData(data);
drawChart(processedData);
});
}
function drawChart(dataArray) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'DateTime');
data.addColumn('number', 'Value');
for (var i = 0; i < dataArray.length; i += 2) {
console.log(dataArray[0]);
data.addRow([dataArray[i], dataArray[i + 1]]);
}
var chart = new google.visualization.AreaChart(document.getElementById('chart'));
chart.draw(data, {
title: "Data Visualization",
isStacked: true,
width: '50%',
height: '50%',
vAxis: {
title: 'Data v-Axis'
},
hAxis: {
title: 'Data h-Axis'
}
})
}