Google GeoChart, JSON and Perl

The Google API GeoChart Map ( is pretty nice widget to generate nice maps based on certain values. It has quite a lot of features and it is very easy to use.

Before we look at the Google API for GeoChart, let’s first set up a script which will get data out of a database and return it in a JSON formatted object.
In this example we will use Perl and three Perl modules:

  • DBI
  • JSON
  • CGI

When converting database values to a JSON object (or text string), it is very important that all data is properly type-casted.
In the following example you will see that we do:

$_->[1] = int($_->[1]) foreach @$data;

This snippet will actually make our INTEGER value into a real integer. The DBI module had returned it as a normal string (that’s just how DBI works).

use strict; use warnings;
use DBI;
use JSON;
use CGI;

my $q = CGI->new;
my $db = DBI->connect("dbi:mysql:host=localhost;db=testdb", 'testuser', 'xxxsecret');

my $sql = "SELECT country_name, count(id) as total from geo_data group by country_name";
my $data = $db->selectall_arrayref($sql);
unshift(@$data, ['Country', 'Attacks']);

my $json = encode_json($data);
print $json;

The above Perl script will be saved as ””.

In the below Javascript example, we will use the Google API for the GeoChart Map and jQuery for making the AJAX call to our Perl script. Since the Perl script already provides the data in a JSON format, we do not need to convert or parse it.
Furthermore the Javascript code is pretty straightforward and based on the example found at, except for the AJAX part.

    google.load('visualization', '1', {packages: ['geochart']});

    function drawVisualization() {
        var options = {
            height: '500',
            width: '1200',
            colorAxis: {minValue: 0,  colors: ['#FFC26B', 
            datalessRegionColor: '#FAFAFA',
            backgroundColor: '#F4EFE7',
            type: 'POST',
            url: "",
            dataType: "json",
            async: false,
            success: function(json_data) {
                var data = google.visualization.arrayToDataTable(json_data);
                var chart = new google.visualization.GeoChart(
                                   document.getElementById('visualization') );

                chart.draw(data, options);

An example of this setup can be found at


Google GeoChart, JSON and Perl — 2 Comments

  1. Just for fun I decided to port this and the following post to the Mojolicious framework, mostly because I thought they were interesting examples. I’m not trying to condemn the continued use of, but rather provide useful comparative examples to those who might want to see them. Cheers!

Leave a Reply

