Google Chart Tools

25. november 2010 by Thomas Stern

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;
    }
public string Label {
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;
} } 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

 

0 comment(s) for “Google Chart Tools”

    Leave comment: