javascriptgoogle-apigoogle-visualizationgoogle-gauges

Adding suffix to google gauge bottom label prevents it from changing


I have a google gauge that retrieves data dynamically from a database with PHP, the problem is that I want the gauge to have a suffix in the bottom label for that I have used:

  // This is what creates the problem 
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);

And this works fine until I have start to change the gauge values over time. Only the pointer moves, the label on the bottom witch says the 'value + %' keeps the same.

Image of the busy gauge

Anyone know how to fix this?!?

Code for the gauge:

function SOC() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['SOC', 10]
  ]);
  var options = {
    width: 250, height: 250,
    redFrom: 0, redTo: 10,
    yellowFrom: 10, yellowTo: 25,
    minorTicks: 5,
    majorTicks: ['0','25','50','75','100']
  };
  var formatter = new google.visualization.NumberFormat({
    suffix: '%',
    fractionDigits: 0
  });
  formatter.format(data, 1);
  var chart = new google.visualization.Gauge(document.getElementById('SOC'));

  chart.draw(data, options);
  setInterval(function() {
    $.ajax({
        url: "soc.php",
        dataType: "JSON",
        data:{},
        success: function(x){
          console.log(x["SOC"]);
          data.setValue(0, 1, x["SOC"] );
          chart.draw(data, options);
        }
    });
    }, 2000);
} 

Solution

  • Try to call formatter.format(data, 1) after updating your data:

    setInterval(function() {
              data.setValue(0, 1, 40 + Math.round(60 * Math.random()));
              formatter.format(data, 1);
              chart.draw(data, options);
            }, 1000);
    

    Check out this fiddle