Home > C#, Javascript > Google Chart Tools

Google Chart Tools

No i haven’t forgotten about my blog, and yes it’s been a while since my last post. So i’m sorry for not answering questions quickly.
So in this post I will have a look at the chart tools google provides, you can read more about here http://code.google.com/apis/chart/   .

In Pentia we have a different tools for monitoring different parameters and i thought i could be fun to have some graphical reprensentation of this, and luckely one of colleagues told me about the chart tools at google. So in this post we have a quick look at this service from google. I will only do the simple piechart but it is possible to build more complex chart.

So since I want different input to the chart tools I will first build a simple interface, and do and simple demo implementation.


interface IChartItem
{
string Label { get; }
string Size { get; }
}

and now to the simple implementation


public class Demo : IChartItem
{
public Demo(string label,string size)
{
Label = label;
Size = size;
}<br>

public string Label
{<br>
get; private set;
}

public string Size
{
get;
private set;
}
}

Now to the glue that combines or more build the url for image that hold our chart.


protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}

protected string ChartSource
{
get
{
return BuildGoogleChartUrl();
}
}

private string BuildGoogleChartUrl()
{
string prefix = "http://chart.apis.google.com/chart?cht=p3&chs=500x300";
string chd = "&chd=t:";
foreach (IChartItem chartItem in ChartItems)
{
chd = String.Format("{0}{1},", chd, chartItem.Size);
}
chd = chd.TrimEnd(',');
string chl = "&chl=";
foreach (IChartItem chartItem in ChartItems)
{
chl = String.Format("{0}{1}|", chl, chartItem.Label);
}
chl = chl.TrimEnd('|');
return String.Format("{0}{1}{2}", prefix, chd,chl);
}

private IEnumerable _chartItems;
private IEnumerable ChartItems
{
get
{
if (_chartItems == null)
_chartItems = InstantiateChartItems();
return _chartItems;<br>
}
}

private IEnumerable InstantiateChartItems()
{
List list = new List();
list.Add(new Demo("20","20"));
list.Add(new Demo("4", "40"));
list.Add(new Demo("50", "50"));
list.Add(new Demo("10", "10"));
return list;
}

And now we can use the url generated as a source for img-tag as this <img src=”<%# ChartSource %>” />

and here is the result

piecahrtexample

Advertisements
Categories: C#, Javascript Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: