使用Socket.io填充谷歌区域图表 - 'google.visualization.DataTable不是构造函数'

时间:2016-04-26 19:20:01

标签: node.js socket.io google-visualization

我使用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不是构造函数”。我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是drawChart被调用两次 来自google.setOnLoadCallbackgetData
如果在getData之前调用google.setOnLoadCallback,则 然后google.visualization.DataTable将无法识别。

此外,建议使用loader.jsjsapi 有关详细信息,请参阅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'
        }
    })
}