javascriptgoogle-visualizationnumber-formattingsuffixgoogle-gauges

Add suffix using "google.visualization.NumberFormat"


Been trying to add a '%' beside the value on a Google Gauge chart, I'm sure it's something stupid I am missing.

Here is what I tried, following another post: Adding a % sign to Google Gauges

google.charts.load('current', {
                    'packages': ['gauge']
                });
                google.charts.setOnLoadCallback(drawChart);

                function drawChart() {

                    var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1Z-eKZJ_XbmnoLYyG4cht40KMo07_CYnLP-hPi1ZBjnw/edit#gid=0');
                    query.send(handleQueryResponse);

                    var options = {
                        redFrom: 0,
                        redTo: 35,
                        yellowFrom: 35,
                        yellowTo: 65,
                        greenFrom: 65,
                        greenTo: 100,
                        minorTicks: 5
                    };
                   var formatter = new google.visualization.NumberFormat( {suffix: '%'} ); formatter.format(data,1);
function handleQueryResponse(response) {
                        var data = response.getDataTable();
                        new google.visualization.Gauge(document.getElementById('gaugechart')).draw(data);
                    }
                }

Any nudge in the right direction would be much appreciated, and please be gentle...

FYI this is my first post here in Stack Exchange, any formatting error or question nono's let me know.


Solution

  • need to wait until the data is returned before trying to use the formatter
    move it inside handleQueryResponse

    google.charts.load('current', {
      callback: function () {
        var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1Z-eKZJ_XbmnoLYyG4cht40KMo07_CYnLP-hPi1ZBjnw/edit#gid=0');
        query.send(handleQueryResponse);
    
        function handleQueryResponse(response) {
          var data = response.getDataTable();
    
          var formatter = new google.visualization.NumberFormat( {pattern: '0', suffix: '%'} );
          formatter.format(data, 1);
    
          var options = {
            redFrom: 0,
            redTo: 35,
            yellowFrom: 35,
            yellowTo: 65,
            greenFrom: 65,
            greenTo: 100,
            minorTicks: 5
          };
    
          new google.visualization.Gauge(document.getElementById('gaugechart')).draw(data, options);
        }
      },
      packages: ['gauge']
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="gaugechart"></div>