简体   繁体   English

如何定期刷新谷歌图表?

[英]How to refresh Google Charts periodically?

Hello, I have a timeline made with google charts, what I want to do is update it every so often, for example every 5 seconds, I get the data from a json, I tried it this way but it didn't work for me:你好,我有一个用谷歌图表制作的时间线,我想做的是每隔一段时间更新一次,例如每 5 秒一次,我从 json 中获取数据,我尝试过这种方式,但它对我不起作用:

setTimeout(function () {
            drawChart();
        }, 5000);

Is there any way to do it?有什么办法吗?

google.load("visualization", "1", {packages: ["timeline"]});
    google.setOnLoadCallback(drawChart);

    // google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        $(".timeline").each(function () {
            var obje = {{ devicejson|safe }};
            var elem = $(this),
                id = elem.attr('id');
            var container = document.getElementById(id);
            var chart = new google.visualization.Timeline(container);
            var dataTable = new google.visualization.DataTable();
            dataTable.addColumn({type: 'string', id: 'Role'});
            dataTable.addColumn({type: 'string', id: 'Name'});
            dataTable.addColumn({type: 'date', id: 'Start'});
            dataTable.addColumn({type: 'date', id: 'End'});
            dataTable.addColumn({type: 'string', id: 'TimeEst'});
            dataTable.addColumn({type: 'string', role: 'style'});
            for (n = 0; n < obje.length; ++n) {
                if (obje[n].device_id == id) {
                    dataTable.addRows([
                        ['Department', obje[n].digitaloutput_user_description, new Date('"' + obje[n].startdatetime + '"'), new Date('"' + obje[n].enddatetime + '"'), obje[n].lighstate_user_description, obje[n].color],
                    ]);
                }
            }

            for (n = 0; n < obje.length; ++n) {
                if (obje[n].device_id == id) {
                    console.log(obje[n].color)

                }
            }

            var options = {
                chartArea: {
                    height: '90%',
                    width: '100%',
                    top: 36,
                    right: 12,
                    bottom: 2,
                    left: 12
                },
                height: 100,
                tooltip: {isHtml: true},
                timeline: {
                    showRowLabels: false,
                },
                avoidOverlappingGridLines: false,
                {#hAxis: {format: 'dd-MMM-yyyy HH:mm:ss'}#}

            };

            var formatTime = new google.visualization.DateFormat({
                pattern: 'yyyy-MM-dd HH:mm:ss a'
            });

            var view = new google.visualization.DataView(dataTable);
            view.setColumns([0, 1, {
                role: 'tooltip',
                type: 'string',
                calc: function (dt, row) {
                    // build tooltip
                    var dateBegin = dt.getValue(row, 2);
                    var dateEnd = dt.getValue(row, 3);
                    var oneHour = (60 * 1000);
                    var duration = (dateEnd.getTime() - dateBegin.getTime()) / oneHour;

                    var tooltip = '<div><div class="ggl-tooltip"><span>';
                    tooltip += dt.getValue(row, 0) + ':</span>&nbsp;' + dt.getValue(row, 1) + '</div>';
                    tooltip += '<div class="ggl-tooltip"><div>' + formatTime.formatValue(dateBegin) + ' - ';
                    tooltip += formatTime.formatValue(dateEnd) + '</div>';
                    tooltip += '<div><span>Duration: </span>' + duration.toFixed(0) + ' minutes</div>';
                    tooltip += '<div><span>Estate: </span>' + dt.getValue(row, 5) + '</div></div>';

                    return tooltip;
                },
                p: {html: true}
            }, 2, 3]);

            google.visualization.events.addListener(chart, 'ready', function () {
                var labels = container.getElementsByTagName('text');
                Array.prototype.forEach.call(labels, function (label) {
                    label.setAttribute('font-weight', 'normal');
                });
            });

            chart.draw(view.toDataTable(), options);


        })
        setTimeout(function () {
            drawChart();
        }, 5000);
    }

for starters, the old version of google charts should no longer be used.首先,不应再使用旧版本的谷歌图表。

replace the old library...更换旧图书馆...

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

with the new library...随着新图书馆...

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

this will only change the load statement.这只会改变load语句。
which can be found in the following snippet...可以在以下代码段中找到...


next, it appears you are loading the data from the server , here...接下来,您似乎正在从服务器加载数据,这里...

var obje = {{ devicejson|safe }};

JavaScript runs on the client . JavaScript 在客户端上运行。
so no matter how many times drawChart is called,所以无论drawChart被调用多少次,
it will always use the same data received from the server on the first page load.它将始终使用在第一页加载时从服务器接收到的相同数据。

instead, try this...相反,试试这个......

create two pages, one that returns the data, and the other that draws the chart.创建两个页面,一个返回数据,另一个绘制图表。
then you can use AJAX to get the data and draw the chart as many times as needed.然后你可以使用AJAX来获取数据并根据需要多次绘制图表。

create a new page, and all you really need in the new page is the following line of code.创建一个新页面,您在新页面中真正需要的是以下代码行。

{{ devicejson|safe }}

aside from any header information, and existing code you're using to get the data to the current page.除了任何标题信息以及您用来将数据获取到当前页面的现有代码之外。
but you don't want to assign it to a variable in the new page.但您不想将其分配给新页面中的变量。
just write the data to the page using the above statement.只需使用上述语句将数据写入页面即可。

then you can use AJAX to get the data and draw the chart.那么你就可以使用 AJAX 来获取数据并绘制图表了。

function getData() {
    $.ajax({
      url: 'get_data.url',   // <-- use url to new page here
      dataType: 'JSON'
    }).done(function (data) {
      drawChart(data);
    });
}

then, wait for the chart's ready event, before calling setTimeout .然后,在调用setTimeout之前等待图表的就绪事件。
because we don't know how long it will take to get the data and draw the chart.因为我们不知道需要多长时间才能拿到数据并绘制图表。
so let's wait for the first chart to finish, before trying again.所以让我们等待第一个图表完成,然后再试一次。

see following snippet...看下面的片段...

google.charts.load('current', {
  packages:['timeline']
}).then(getData);            // <-- load google charts, then get the data

function getData() {
    $.ajax({
      url: 'get_data.url',   // <-- use url to new page here
      dataType: 'JSON'
    }).done(function (data) {
      drawChart(data);       // <-- draw chart with data from new page
    });
}


function drawChart(obje) {
    $(".timeline").each(function () {
        var elem = $(this),
            id = elem.attr('id');
        var container = document.getElementById(id);
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn({type: 'string', id: 'Role'});
        dataTable.addColumn({type: 'string', id: 'Name'});
        dataTable.addColumn({type: 'date', id: 'Start'});
        dataTable.addColumn({type: 'date', id: 'End'});
        dataTable.addColumn({type: 'string', id: 'TimeEst'});
        dataTable.addColumn({type: 'string', role: 'style'});
        for (n = 0; n < obje.length; ++n) {
            if (obje[n].device_id == id) {
                dataTable.addRows([
                    ['Department', obje[n].digitaloutput_user_description, new Date('"' + obje[n].startdatetime + '"'), new Date('"' + obje[n].enddatetime + '"'), obje[n].lighstate_user_description, obje[n].color],
                ]);
            }
        }

        for (n = 0; n < obje.length; ++n) {
            if (obje[n].device_id == id) {
                console.log(obje[n].color)

            }
        }

        var options = {
            chartArea: {
                height: '90%',
                width: '100%',
                top: 36,
                right: 12,
                bottom: 2,
                left: 12
            },
            height: 100,
            tooltip: {isHtml: true},
            timeline: {
                showRowLabels: false,
            },
            avoidOverlappingGridLines: false,
            {#hAxis: {format: 'dd-MMM-yyyy HH:mm:ss'}#}

        };

        var formatTime = new google.visualization.DateFormat({
            pattern: 'yyyy-MM-dd HH:mm:ss a'
        });

        var view = new google.visualization.DataView(dataTable);
        view.setColumns([0, 1, {
            role: 'tooltip',
            type: 'string',
            calc: function (dt, row) {
                // build tooltip
                var dateBegin = dt.getValue(row, 2);
                var dateEnd = dt.getValue(row, 3);
                var oneHour = (60 * 1000);
                var duration = (dateEnd.getTime() - dateBegin.getTime()) / oneHour;

                var tooltip = '<div><div class="ggl-tooltip"><span>';
                tooltip += dt.getValue(row, 0) + ':</span>&nbsp;' + dt.getValue(row, 1) + '</div>';
                tooltip += '<div class="ggl-tooltip"><div>' + formatTime.formatValue(dateBegin) + ' - ';
                tooltip += formatTime.formatValue(dateEnd) + '</div>';
                tooltip += '<div><span>Duration: </span>' + duration.toFixed(0) + ' minutes</div>';
                tooltip += '<div><span>Estate: </span>' + dt.getValue(row, 5) + '</div></div>';

                return tooltip;
            },
            p: {html: true}
        }, 2, 3]);

        google.visualization.events.addListener(chart, 'ready', function () {
            var labels = container.getElementsByTagName('text');
            Array.prototype.forEach.call(labels, function (label) {
                label.setAttribute('font-weight', 'normal');
            });

            setTimeout(getData, 5000);       // <-- get data and draw again in 5 seconds
        });

        chart.draw(view.toDataTable(), options);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM