viernes, 7 de diciembre de 2007

Nueva API de Google para gráficas

Google ha lanzado su nueva API para crear gráficas dinámicamente (Google Chart API). Tiene aún muchas limitaciones que me impiden substituir las aplicaciones que usaba hasta ahora: por ejemplo, sólo admite valores de 0 a 100 y no muestra etiquetas con los valores en cada punto, sólo son gráficos en PNG sin animación, etc. Seguro que en breve harán muchos de estos avances.

De momento, para los que quieran usar PHP para generar gráficos de evolución, aquí les paso un PHP que he creado para poder simular el uso de valores superiores a 100:



echo google_chart($values, null, $labels);

function google_chart($values, $max=null, $labels=null, $cht="lc", $width=500 , $height=200, $img_tag = true ) {

if(!is_array($values)) return "ERROR";

$max = $max ? $max : max($values);
$chd = simpleEncode($values, $max);
$chs = $width."x".$height;


$url = "http://chart.apis.google.com/chart?";
$url .= "cht=".$cht;
$url .= "&chs=".$chs;
$url .= "&chd=".$chd;

if($labels) {
$url .= "&chxt=x&chxl=0:|".implode($labels,"|");
}

if($img_tag) return '';
else return $url;
}

function simpleEncode($values, $maxValue) {

$simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$count_simpleEncoding = strlen($simpleEncoding)-1;
$chartData = "s:";

for($i=0; $i $currentValue = $values[$i];
if (is_numeric($currentValue) && $currentValue >= 0) {
$position = round( $count_simpleEncoding * $currentValue / $maxValue , 0);
$encoded = substr($simpleEncoding, $position, 1);
$chartData .= $encoded;
}
else {
$chartData .= '_';
}
}
return $chartData;
}

No hay comentarios: