Thursday, June 12, 2008

Using Google Charts with GBIF stats data

While developing the Iphone UI I wanted to give a try to the Google Charts API. This is a pretty amazing powerful API to create easily charts. The charts always come back as simple images so no chance to create interactive stats like with Flash and specially Flex Charting. In any case this is so simple to use that I had to give it a try.

But lets take a look at one example. You want to have a world map with different colors per country depending on how much occurrences there are in GBIF database for a certain taxon, uff!. For example Pinales:


Well it is pretty simple, the URL looks like this:

http://chart.apis.google.com/chart?cht=t&chs=300x163&chco=ffffff,edf0d4,13390a&chtm=world&chf=bg,s,EAF7FE&chld=
GBDEUSNOFRCZPLSEATAUESIEPGMXNLKRCACHBELUNZITNCIMILIDPSJOFILIJPRUD
KSICRGRSYPEVNTWPTHNCNNIBOMGECHUGIARGTSKPYSVVEKPTZCOPAMABYTRDOM
MBRLABZEGCLLBZAGEKEMYHTADAMINPHLTSBPRUGVAKZTHMKGLUZUABGGFCDPK
ALETTJHRCMKGAQSZNFRSZMBILYGYMCSMIRLSCYROAZEEVUMZDZISNGMWSAZWLV
GANPLKKHTCBTMN&chd=s:6aZTNMLLGEDDCCCCCBBBBBBBBBBAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAA

Well it looks complicate at first look but this is just because of the encoding of the data to represent. Step by step is easier, this how it was done:

1) Connect to the GBIF API service to retrieve occurrences per taxon and per country:

2) Generate the URL for charting:

$churl = "http://chart.apis.google.com/chart?cht=t&chs=300x163&chco=ffffff,edf0d4,13390a&chtm=world&chf=bg,s,EAF7FE";
$country_list="";
$country_data="";
foreach($json['Resultset']['Result'] as $country) {
$country_list.=$country['id'];
$country_data.=$country['count'].",";
}
$country_data = substr($country_data,0,strlen($country_data)-1);
$churl .= "&chld=".$country_list;
$churl .= google_chart_encode($country_data,"s");


Thats it! You got the URL. this was done in PHP but it could had even been done in Javascript

I also used it to represent the amount of data per country currently avaialble in GBIF. If anybody is interested please let me know and I will provide the code.



No comments: