简体   繁体   English

在Google图表中动态加载数据

[英]Dynamic data loading in Google Charts

I have a google chart which I am feeding with JSON data as follows: 我有一个谷歌图表,我正在用JSON数据进行以下馈送:

      var visualization;
      var chart_url = 'http://XXappspot.com/data?v=load1&v=load5&v=load15&span=100';

      function drawVisualization() {
        var query = new google.visualization.Query(chart_url);
        query.send(handleQueryResponse);
      }

      function handleQueryResponse(response) {
        if (response.isError()) {
          alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
          return;
        }

        var data = response.getDataTable();
        var formatter = new google.visualization.DateFormat( { pattern: 'd MMM, HH:mm:ss' } );
        formatter.format(data, 0);
        visualization = new google.visualization.LineChart(document.getElementById('visualization'));
        visualization.draw(data, { hAxis: { format: "HH:mm" }});
      }

      google.setOnLoadCallback(drawVisualization);

Now I would like to add buttons on the page which will change the data source (request other data) and refresh the chart. 现在,我想在页面上添加按钮,这些按钮将更改数据源(请求其他数据)并刷新图表。 I have seen the use of controls in the documentation but they seem to work only with data already downloaded, while I would like to re-download different data. 我已经在文档中看到了控件的使用,但是它们似乎仅适用于已经下载的数据,而我想重新下载其他数据。 Any ideas how to do this? 任何想法如何做到这一点?

Bonus question: is there a way to change the timezone of the X axis? 额外的问题:是否可以更改X轴的时区? No, adding "timeZone" to the hAxis options does not work. 否,将“ timeZone”添加到hAxis选项不起作用。 Preferably, I would like to show datetime data in the local timezone of the user. 最好是,我想在用户的本地时区显示日期时间数据。

Add an event listener to the buttons on your page that changes chart_url and calls drawVisualization . 将事件侦听器添加到页面上的按钮,以更改chart_url并调用drawVisualization

function changeUrl () {
    chart_url = 'http://new.url.com';
    drawVisualization();
}

As far as changing the timezone of the data, by default the Date objects are created and displayed in the local timezone. 至于更改数据的时区,默认情况下会创建Date对象并将其显示在本地时区中。 If your data represents another timezone, you must enter it as UTC time, or use a function to convert the dates to UTC time: 如果数据代表另一个时区,则必须将其输入为UTC时间,或使用函数将日期转换为UTC时间:

function drawCharts () {
    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Date and time');
    data.addColumn('number', 'Value');

    // add 100 rows of pseudo-random-walk data
    var val = 50, hour, minute;
    for (var i = 0; i < 100; i++) {
        val += ~~(Math.random() * 5) * Math.pow(-1, ~~(Math.random() * 2));
        if (val < 0) {
            val += 5;
        }
        else if (val > 100) {
            val -= 5;
        }
        data.addRow([new Date(2013, 0, 1, i), val]);
    }

    // the time entered was supposed to be UTC time, but is entered as local time
    // this function updates the Date objects to the proper UTC time
    function localDateToUTCDate (d) {
        d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
    }
    for (var i = 0; i < data.getNumberOfRows(); i++) {
        data.setValue(i, 0, localDateToUTCDate(data.getValue(i, 0)));
    }

    var chart = new google.visualization.ChartWrapper({
        chartType: 'LineChart',
        containerId: 'chart_div',
        dataTable: data,
        options: {
            height: 400,
            width: 600,
            vAxis: {
                minValue: 0,
                maxValue: 100
            }
        }
    });
    chart.draw();
}
google.load('visualization', '1', {packages:['controls'], callback: drawCharts});

see it working here: http://jsfiddle.net/asgallant/4vDVn/ 看到它在这里工作: http : //jsfiddle.net/asgallant/4vDVn/

So given the problem that the dates are stored on the server and transmitted to the client in UTC, whereas the client interprets the UTC data as local time, the solution is to process the JSON-fed DataTable on the client side so that the input parameters to date are correctly considered as UTC: 因此,考虑到日期存储在服务器上并以UTC格式传输到客户端,而客户端将UTC数据解释为本地时间这一问题,解决方案是在客户端处理JSON填充的DataTable,以便输入参数迄今为止,已正确地视为UTC:

// shift dates (1st column) to local timezone
for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
  var d = data.getValue(y, 0);
  d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
  data.setValue(y, 0, d)
}

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

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