API Example
Chart your data with the Google Charts API
- Fetch a date-range of data for a user
- Build array of dates/step counts
- Build Google Chart
- API requests - Fetch data for the last 7 days
- http://walkertracker.com/api/ben.serialized/view/20081005,20081012
View the example - enter a username:
PHP Code
<?php
//This function fetches data from Walker Tracker API using CURL
function wt_api_request($username,$data_format,$method,$date_range="")
{
$api_url = "http://walkertracker.com/api/";
$api_request = $api_url . $username . "." . $data_format ."/".$method;
if($date_range !="")
{
$api_request .= "/" . $date_range;
}
$ch = curl_init();
$timeout = 10; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $api_request);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$curl_contents = @(curl_exec($ch));
curl_close($ch);
return $curl_contents;
}
//this function unserializes php, or shows you the error
function convert_to_array($wt_data)
{
$wt_data = unserialize($wt_data);
if(array_key_exists("error",$wt_data))
{
echo "ERROR: ".print_r($wt_data);
exit;
}else{
return $wt_data;
}
}
//get the last seven days, put it into this format: 20071205,20071212
$date_range = date("Ymd",mktime (0,0,0,date("m"),date("d")-7)).",".date("Ymd");
//Using php function above, wt_api_request:
$my_data = wt_api_request($tested_username,"serialized","view",$date_range);
$my_data = convert_to_array($my_data);
//google charts run from 1 at the bottom to 100 at the top.
//To fit our data on here correctly, divide by
//an appropriate number that will put a data point (such as 11,000 steps)
//to match a scale of 1-100. Dividing it by 500 will yield 22.
$chart_scale = 500;
//this next bit gets your average, fits it to the chart scale, and gives it two points
//on the y access for google's chart.
// The y access points have to be slightly different otherwise nothing is drawn
//this range is computed as 0 on the bottom, 1 on the top.
$my_average = number_format($my_data["average"]/($chart_scale*100),1);
$my_average_y = $my_average +.01;
//array iterator
$i=0;
//create an array to hold step data
$stepdata = array();
//another to hold the date
$stepdate = array();
//loop through days
if(is_array($my_data))
{
foreach ($my_data as $key => $value) {
if(is_numeric($key))
{
$stepdata[$i]= number_format($value["steps"]/$chart_scale,1);
$stepdate[$i]= date("D d",strtotime($value["date"]));
$i++;
}
}
}
}
?>
Build the Google Chart image tag with the returned data.
<img src="http://chart.apis.google.com/chart?
chs=340x175
&chd=t:<?=implode(",", $stepdata)?>
&cht=lc
&chm=r,000000,0,<?=$my_average?>,<?=$my_average_y?>
&chbh=18,28
&chf=c,s,FFFFFF|bg,s,a6a6a6
&chtt=<?=$tested_username?>:+1+Week+of+Steps
&chxt=x,y
&chxl=0:|<?=implode("|",$stepdate)?>|1:|0k|10k|20k|30k|40k|50k
">
See Google's Chart API for an explanation of how to build the chart.
24 Ways also has a great article on Google Charts