A simple Google Charts API "framework"

The Google Charts API is a useful little tool for generating charts. The “API” is actually just a set of parameters you pass to a single URL endpoint: http://chart.apis.google.com/chart

sample chart

It’s a very capable API, and you could write an entire framework around it (as some people have), but I don’t think it’s necessary. A few little helper functions and Google’s documentation is all you really need. Here’s the heart of my “framework” in JavaScript:

function gchart_build(options)
{
    var params = [];
    for (option in options)
        params.push(option + "=" + options[option]);
    return "http://chart.apis.google.com/chart?" + params.join("&");
}

And PHP:

function gchart_build($options)
{
    $params = array();
    foreach ($options as $option => $value)
        $params[] = $option . "=". $value;
    return "http://chart.apis.google.com/chart?" . implode("&", $params);
}

And here’s a simple bar chart example in PHP:

$chart_url = gchart_build(array(
    "cht"   => "bvs",
    "chs"   => "400×250",
    "chbh"  => "14,2,0",
    "chd"   => "t:3,4,4,1,3,2,2,0,1,3,11,5,7,5,5,7,7,5,3,2,3,3,6,6",
    "chds"  => "0,11"
));

The nice thing about this “frameworks” is it takes 30 seconds to implement in many languages, and the actual API is identical across every language, since it just uses a hash object and the original API as a very simple domain-specific language.

This could be improved with a few more helper functions for different parts of the Google Chart API, but this function remains the most important.

Here’s a simple testbed for trying out the JavaScript version. Simple edit the JavaScript and click “Update!” to see the results:
gchart_tester.html