Tuesday, 25 June 2013

Google Charts tutorial

This short tutorial describes how to create chart using Google charts api
1) First of all  need to include:
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

2) Add  div <div id="chart_div" style="width: 800px; height: 500px;"></div>

3) Create line chart using json data format:

 
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
    function drawChart() {
      var jsonData = $.ajax({
                      url: "get_data_json",
                      dataType:"json",
                      type: 'GET',
                      async: false
                      }).responseText; 

      var data = new google.visualization.DataTable(jsonData);
      options = {
          title: 'Installations / Registrations',
      };

      chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
   }  
ajax request has following data frmat :
 
{
       cols: [{id: 'month', label: 'Month', type: 'string'},
              {id: 'installs', label: 'Installs', type: 'number'}
              {id: 'registrations', label: 'Registrations', type: 'number'}],
       rows: [{c:[{v: '11'}, {v: 111},{v: 222}]},
              {c:[{v: '2'}, {v: 22},{v: 44}]}
              ]

  }
 
 4)Create geochart using array data format:
 
   google.load('visualization', '1', {'packages': ['geochart']});
   google.setOnLoadCallback(drawChart);
   function drawChart() {
      $.ajax({
                  url: "get_by_country_json",
                  type: 'GET',
                  async: false,
                  success: function(result) {
                         createChartFromData(result);
                         var data = new google.visualization.DataTable();
                         data.addColumn('string', 'Country');
                         data.addColumn('number', 'Installs');
                         data.addRows($.parseJSON( '['+result +']'));
                         chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
                         options = {};
                         chart.draw(data, options);
                    },
                   error:  function(xhr, str){
                        alert("Some error!");
                    }
              });
          } 

 ajax request has folowing data foramt :
 
  ['US', 200],['RU', 111],['BR', 33]




 References:
https://developers.google.com/chart/interactive/docs/gallery
https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart
https://google-developers.appspot.com/chart/interactive/docs/gallery/geochart

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. please send me nxa0000@gmail.com

    ReplyDelete