简体   繁体   中英

Dynamic data loading in Google Charts

I have a google chart which I am feeding with JSON data as follows:

      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? No, adding "timeZone" to the hAxis options does not work. 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 .

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. If your data represents another timezone, you must enter it as UTC time, or use a function to convert the dates to UTC time:

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/

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:

// 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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