2013-01-14 Javascript

I just rewrote my Tag Cloud to use the Google Treemap.

What it does is the following:

  1. The cloud action runs the old code (text representation).
  2. The tagcloud action runs the new code.
  3. The new code basically takes the example Google Treemap and replaces the data with my tags. These tags are not nested.
  4. On click, we call the tag action which shows the last blog pages with that tag.

Try it! → Tag Cloud. (I realize that the tag cloud isn’t very interesting in and of itself. I just enjoyed using the Google tools and learning a little bit of Javascript on the way.)

$Action{cloud} = $Action{tagcloud};
$Action{tagcloud} = \&MyTagCloud;

sub MyTagCloud {
  print GetHeader('', T('Tag Cloud'), '');
  # open the DB file
  require DB_File;
  tie %h, "DB_File", $TagFile;
  my $max = 0;
  my $min = 0;
  my %count = ();
  foreach my $tag (grep !/^_/, keys %h) {
    $count{$tag} = split(/$FS/, $h{$tag});
    $max = $count{$tag} if $count{$tag} > $max;
    $min = $count{$tag} if not $min or $count{$tag} < $min;
  untie %h;
  # ignore 90% of all tags
  my @values = sort values %count;
  $min = GetParam('min', $values[int($#values * 0.9)]);
  # https://developers.google.com/chart/interactive/docs/gallery/treemap
  print <<EOT;
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["treemap"]});
      function drawChart() {
        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
          ['Location', 'Parent', 'Mentions', ''],
          ['Tags', null, 0, 0],
  foreach my $tag (sort keys %count) {
    my $n = $count{$tag};
    next unless $n > $min;
    print "          ['$tag', 'Tags', $n, 0],\n";
  print <<EOT;
        // Create and draw the visualization.
        var tree = new google.visualization.TreeMap(document.getElementById('treemap'));
        google.visualization.events.addListener(tree, 'select', selectHandler);
        function selectHandler() {
          var selection = tree.getSelection();
          var item = selection[0];
          window.location = "/alex?action=tag;id=" + data.getValue(item.row,0);
  print $q->start_div({-class=>'content cloud'});
  print $q->p(ScriptLink('action=tagcloud;min=0', T('Include all tags')),
              Ts('(currently showing tags with more than %s occurences)', $min));
  print $q->p(Ts('Or switch to a %s.', ScriptLink('action=cloud', T('text format'))));
  print $q->start_div({-id=>'treemap', -style=>'height: 1000px;'});
  print $q->end_div();
  print $q->end_div();



Please make sure you contribute only your own work, or work licensed under the GNU Free Documentation License. See Info for text formatting rules. You can edit the comment page if you need to fix typos. You can subscribe to new comments by email without leaving a comment.

To save this page you must answer this question:

Please say HELLO.