Real-time changing point chart with Google Charts

一曲冷凌霜 提交于 2021-02-07 07:55:03

问题


I have a problem with google charts. I have struggled with this problem for two few days now and I can't seem to find a solution.

I'm suppose to create a monitoring system where I can see changing line chart that has two lines in it. I'm generating the data in the JS code (at least for now).

I don't know what I'm doing wrong. I can make the chart visible with really simple static example but as soon as I'm trying to add some data to the chart it stops drawing.

Error with this current version is:

"uncaught TypeError: Cannot read property 'length' of undefined"

but this is nth time I have tried different method of adding more data to the chart and also nth different error. So if someone knows how adding data to google chart works, it would be great to hear.

Thanks in advance.

setInterval(function() {  
  //this is how I create a random data and call the drawChart function.
  var temperature = (Math.random() * (35 - 30) + 30).toFixed(1),
      humidity = (Math.random() * (40 - 15) + 15).toFixed(1),
      timestamp = new Date();
  google.charts.setOnLoadCallback(drawChart(timestamp, temperature, humidity));
}, 5000);

function drawChart(timestamp, temperature, humidity) {
  //Cast temperature to proper format for the chart
  //This works...don't understand why but it does.
  temperature = parseFloat("temperature");
  humidity = parseFloat("humidity");  

  // Define the chart to be drawn.
  var data = new google.visualization.DataTable();

  if (data[0].length == 0) {
    var datetime = new Date();
    data.addColumn('datetime', 'Time');
    data.addColumn('number', 'Temperature');
    data.addColumn('number', 'Humidity');
    data.addRow(datetime, 0, 0);

    var options = {
      'title' : 'Temperature and Humidity',
      hAxis: {title: 'Time'},
      vAxis: {title: 'Temperature and Humidity'},   
      'width':550,
      'height':400	  
    };
  }
  data.addRow(timestamp, temperature, humidity);
  // Instantiate and draw the chart.
  var chart = new google.visualization.LineChart(document.getElementById('monitor-chart'));
  chart.draw(data, options);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Projekti 1, sivusto</title>

    <!-- Latest BOOTSTRAP minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <!-- Latest BOOTSTRAP JC-->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!-- JS Generate new data Class -->
    <script type="text/javascript" src="js/generate_data.js"></script>

    <!-- GOOGLE CHARTS visualization -->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {packages: ['corechart','line']});  
    </script>

    <!-- My css file -->
    <link rel="stylesheet" type="text/css" href="css/ulkoasu.css"/>

  </head>
  <body>
    <article>
      <h1>This is Monitor content</h1>
      <div id="monitor-data"></div>
      <div id="monitor-chart"></div>
    </article>
  </body>
</html>

回答1:


first, the argument for setOnLoadCallback should be a reference to a function, like follows...

google.charts.setOnLoadCallback(drawChart);

not the result of a function call...

google.charts.setOnLoadCallback(drawChart(timestamp, temperature, humidity));

and setOnLoadCallback is typically only used once per page load,
after the callback finishes for the first time, this method is no longer needed

regardless, the callback can be added to the load statement
setOnLoadCallback isn't really needed


other errors include the use of addRow --> data.addRow(timestamp, temperature, humidity);

the column values should be passed in an array...

data.addRow([timestamp, temperature, humidity]);

recommend setup similar to the following -- when the callback fires,
all the resources, such as the chart, options, and data table are created

drawChart is simply used to add one row and draw the chart

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var chart = new google.visualization.LineChart(document.getElementById('monitor-chart'));

    var options = {'title' : 'Temperature and Humidity',
      animation: {
        duration: 1000,
        easing: 'out',
        startup: true
      },
      hAxis: {
        title: 'Time'
      },
      vAxis: {
        title: 'Temperature and Humidity'
      },
      height: 400
    };

    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Time');
    data.addColumn('number', 'Temperature');
    data.addColumn('number', 'Humidity');

    var formatDate = new google.visualization.DateFormat({pattern: 'hh:mm:ss'});
    var formatNumber = new google.visualization.NumberFormat({pattern: '#,##0.0'});

    getTemp();
    setInterval(getTemp, 5000);
    function getTemp() {
      var temperature = (Math.random() * (35 - 30) + 30);
      var humidity = (Math.random() * (40 - 15) + 15);
      var timestamp = new Date();
      drawChart(timestamp, temperature, humidity);
    }

    function drawChart(timestamp, temperature, humidity) {
      data.addRow([timestamp, temperature, humidity]);

      formatDate.format(data, 0);
      formatNumber.format(data, 1);
      formatNumber.format(data, 2);

      chart.draw(data, options);
    }
  },
  packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="monitor-chart"></div>


来源:https://stackoverflow.com/questions/40928712/real-time-changing-point-chart-with-google-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!