How to write a custom formatter for Google DataTables (for use on visualisation api)
Asked Answered
G

3

19

I'm looking to format my data in which I replace numbers with icons.

As far as I can tell Google do not currently have a formatter to do so:

http://code.google.com/apis/chart/interactive/docs/reference.html#formatters

There is a brief mention within the documents about custom formatters, but I cannot seem to find any documents on how to begin writting a custom formatters.

Can anyone point me in the right direction?

There is a similar question on StackOverflow: Write a custom formatter for Google Charts Api . However the question was resolved simply using the built-in formatters (which I don't think I can use).

Gi answered 2/9, 2011 at 16:18 Comment(1)
The custom formatters mentioned in the documentation probably refer to custom format patterns. For custom format code, see the answers below.Decurved
J
24

I don't think you'll be able to make the current formatters to do what you want, but you should be able to make your own formatter easily enough. I put together iconFormatter below for a sample - this could be adjusted to do whatever you need really.

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['table']});
    </script>
    <script type="text/javascript">
      /**
      * Gviz icon formatter
      * @param {Object<Number, String>} Map of numbers to icon URIs
      */
      var iconFormatter = function(iconMap) {
        this.iconMap = iconMap;
      }
      /**
       * Formats a gviz DataTable column
       * @param {Object} dt DataTable to format
       * @param {Number} column index number
       */
      iconFormatter.prototype.format = function(dt, column) {
        for (var i=0;i<dt.getNumberOfRows();i++) {
          var formattedValue = this.iconMap[dt.getValue(i, column)];
          var htmlString = "<img src="+formattedValue+" />";
          dt.setFormattedValue(i, column, htmlString);
          // underlying value preserved
          console.log(dt.getValue(i, column)); 
        }
      }
    </script>
    <script>
      function drawVisualization() {
        // Create and populate the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('number', 'Height');
        data.addRows(3);
        data.setCell(0, 0, 'Tong Ning mu');
        data.setCell(1, 0, 'Huang Ang fa');
        data.setCell(2, 0, 'Teng nu');
        data.setCell(0, 1, 174);
        data.setCell(1, 1, 523);
        data.setCell(2, 1, 86);

        var iconMap = {
          174: "http://farm1.static.flickr.com/76/buddyicons/[email protected]?1149480603",
          523: "http://farm1.static.flickr.com/28/buddyicons/[email protected]?1129271399",
          86: "http://farm3.static.flickr.com/2698/buddyicons/[email protected]?1303489082"
          // other numbers
        }

        // Create and draw the visualization.
        visualization = new google.visualization.Table(document.getElementById('table'));
        // apply our formatter, just like normal
        var formatter = new iconFormatter(iconMap);
        formatter.format(data, 1);
        // allow html, just like any html formatter will require
        visualization.draw(data, {allowHtml: true});
      }
      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body>
    <div id="table"></div>
  </body>
</html>

Hope that helps.

Jacquettajacquette answered 14/9, 2011 at 13:25 Comment(5)
Looks sweet! Thanks for the indepth answer!Gi
Hi @oli, thanks it worked a treat! Just a bit of a follow up question (hope you don't mind), I was trying to adapt your example to be able to also wrap the icon with a href (if the href is passed in), but I couldn't seem to figure it out. Any hints on how to get started?Gi
Glad it worked @AlexKey. You should be able to modify the variable htmlString to include an a tag, allowing for a link. var htmlString = "<a href='http://www.google.com' target='_blank'><img src="+formattedValue+" /></a>";Jacquettajacquette
Thanks @Jacquettajacquette I'll post my code once I get a chance just in case it helps anyone. thanks for your help.Gi
Thanks @oil! this works great, just one question. It does not apply the format to the labels on the axis (I'm using it with a LineChart), do you know if that is possible?Driven
D
4

The built-in DataTable formatters currently only allow customization with formatting strings (patterns). Customization with a callback function is not supported. Here is a formatter class that supports a callback function.

/**
 * Custom formatter class for Google Visualization DataTable
 * Can be used like a built-in formatters when they are not enough. 
 * https://developers.google.com/chart/interactive/docs/reference#formatters
 * Changes the displayed/formatted value. The value itself remains unchanged.
 *
 * @param function() custom value conversion function
 *  this function 
 *  - takes one value as input (the original value) and 
 *  - returns the formatted value
 */
var CustomFormatter = function(formatValue) {
  this.formatValue = formatValue;
}

/**
 * Formats a Google DataTable column
 * @param {Object} dt DataTable to format
 * @param {Number} column index number
 */
CustomFormatter.prototype.format = function(dt, column) {
  for (var i = 0; i < dt.getNumberOfRows(); i++) {
    var value = dt.getValue(i, column);
    dt.setFormattedValue(i, column, this.formatValue(value));
  }
}

This class can be used like the built-in formatter functions, but with a callback function in the constructor, like this one that converts a number to HH:MM:SS

var customFormatter = new CustomFormatter(function(value) {
    var hours = parseInt(value / 3600) % 24;
    var minutes = parseInt(value / 60) % 60;
    var seconds = value % 60;
    return (hours < 10 ? "0" + hours : hours) +
      ":" + (minutes < 10 ? "0" + minutes : minutes) +
      ":" + (seconds < 10 ? "0" + seconds : seconds);
});
customFormatter.format(dataTable, 1);

Here's the working demo fiddle: http://jsfiddle.net/o5tdt2r8/10/

Alternatively use addColumn in a DataView, as documented in an other answer.

Thanks to @oli's for the original answer. I separated the custom callback formatting function from the generic formatter.

Decurved answered 6/6, 2016 at 19:53 Comment(2)
Nice, good tip Paul. I'm in a different world now so unable to test it out, but looks good to me thanks for sharing.Gi
Awesome piece of work @Decurved thank you, works great!Kissee
D
3

Unlike a DataTable, a DataView allows to define computed columns through SetColumns

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

google.charts.setOnLoadCallback(function() {
  // Create and populate the data table.
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'Name');
  dataTable.addColumn('number', 'Icon Nr');
  dataTable.addRow(['Tong Ning mu', 174]);
  dataTable.addRow(['Huang Ang fa', 523]);
  dataTable.addRow(['Teng nu', 86]);

  // Create and define the data view with custom formatter in the calc property
  var dataView = new google.visualization.DataView(dataTable);
  dataView.setColumns([0, {
    type: 'string',
    label: 'Icon',
    calc: function(dataTable, rowNr) {
      var iconMap = {
        174: "http://farm1.static.flickr.com/76/buddyicons/[email protected]?1149480603",
        523: "http://farm1.static.flickr.com/28/buddyicons/[email protected]?1129271399",
        86: "http://farm3.static.flickr.com/2698/buddyicons/[email protected]?1303489082"
      }
      var value = dataTable.getValue(rowNr, 1); // 1 is the column
      var formattedValue = iconMap[value]; // convert
      var htmlString = "<img src=" + formattedValue + " />"; // wrap
      // console.log(rowNr, value, formattedValue); // debug
      return htmlString;
    }
  }]);

  // Create and draw the visualization.
  visualization = new google.visualization.Table(document.getElementById('table'));
  visualization.draw(dataView, {
    allowHtml: true // allow html, just like any html formatter will require
  });
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table"></div>
Decurved answered 8/6, 2016 at 11:49 Comment(1)
Again another great answer!Kissee

© 2022 - 2024 — McMap. All rights reserved.