Implementation Of Google Charts In SharePoint 2013

In this article, you will learn about the implementation of Google Charts in SharePoint 2013.

Overview of Google Charts 

Google Chart tools are powerful, simple to use, and free. They have many features namely:

  • Rich Gallery-  A variety of charts, we can choose the best fit for our data.
  • Customizable- We can make our own charts and configure with different set of features.
  • Cross browser compatibility- Can be used across various Browsers.
  • Dynamic Data- Connects a variety of data connection tools and protocols.

Basic Library Loading

  1. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
  2. <script type="text/javascript">  
  3.     google.charts.load('current', {  
  4.         packages: ['corechart']  
  5.     });  
  6.     google.charts.setOnLoadCallback(drawChart);...  
  7. </script>  
  • The first line loads the loader file itself. Once it is loaded, we can use how many charts we want.
  • The first argument in google.charts.load is the version number, which we are using, ‘’current’,’ which indicates to take the latest official release of Google Charts to be loaded, second argument is the packages of charts to be loaded ,”corechart” includes all the basic charts like Pie Chart, Bar Chart, Area Chart etc.
  • After the charts have been loaded successfully, we are calling a function called drawchart, which is a callback function after loading.

Basic Chart Implementation in HTML page

The code given below generates Pie Chart. 

  1. <html>  
  2.   
  3. <head>  
  4.     <!--Load the AJAX API-->  
  5.     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
  6.     <script type="text/javascript">  
  7.         // Load the Visualization API and the piechart package.  
  8.         google.charts.load('current', {  
  9.             packages: ['corechart']  
  10.         });  
  11.         // Set a callback to run when the Google Visualization API is loaded.  
  12.         google.charts.setOnLoadCallback(drawChart);  
  13.         // Callback that creates and populates a data table,  
  14.         // instantiates the pie chart, passes in the data and  
  15.         // draws it.  
  16.         function drawChart() {  
  17.             // Create the data table.  
  18.             var data = new google.visualization.DataTable();  
  19.             data.addColumn('string''Topping');  
  20.             data.addColumn('number''Slices');  
  21.             data.addRows(4);  
  22.             data.setCell(0, 0, "mashroom");  
  23.             data.setCell(0, 1, 4);  
  24.             data.setCell(1, 0, "Cheese");  
  25.             data.setCell(1, 1, 3);  
  26.             data.setCell(2, 0, "Mixedveg");  
  27.             data.setCell(2, 1, 2);  
  28.             data.setCell(3, 0, "Merghartia");  
  29.             data.setCell(3, 1, 1);  
  30.             // Set chart options  
  31.             var options = {  
  32.                 'title''How Much Pizza I Ate Last Night',  
  33.                 'width': 400,  
  34.                 'height': 300  
  35.             };  
  36.             // Instantiate and draw our chart, passing in some options.  
  37.             var chart = new google.visualization.PieChart(document.getElementById('chart_div'));  
  38.             chart.draw(data, options);  
  39.         }  
  40.     </script>  
  41. </head>  
  42.   
  43. <body> //Div that will hold the pie chart  
  44.     <div id="chart_div" style="width:400; height:300"></div>  
  45. </body>  
  46.   
  47. </html>   

To set the data, we are using google.visualization.datatable, which stores the data in tabular structure and in the example given above for each of the cells, we are setting the value after which we are providing the title, width and height of the chart to displayed

Finally, creating the instance of google.visualization.piechart by passing an appropriate div element, which holds the Pie Chart, calling chart.draw() function will generate the chart.

Preparation of SharePoint data for Google Charts

In order to implement the Google Chart in SharePoint we must first create a data source which can used to generate the chart and can be dynamic too. To create a data source we can create a custom list with two columns of type strings and numbers respectively. String type column  is to hold labels for pie chart and number type is for the value for each of the labels.

To fetch the data from SharePoint list, JavaScript object model can be used and the code given below demonstrates the fetching of data from the custom list and pushing the values in to two arrays, one which holds labels for the chart and other the values (tasks array is holding the labels, hours array is holding the values). 

  1. var hours = [];  
  2. var tasks = [];  
  3. SP.SOD.executeFunc('sp.js''SP.ClientContext', Test);  
  4.   
  5. function Test() {  
  6.     var clientcontext = new SP.ClientContext();  
  7.     var web = clientcontext.get_web();  
  8.     var list = web.get_lists().getByTitle('ChartList'); //replace this with your list name //  
  9.     listitems = list.getItems(SP.CamlQuery.createAllItemsQuery());  
  10.     clientcontext.load(listitems);  
  11.     clientcontext.executeQueryAsync(success, failure);  
  12. }  
  13.   
  14. function success() {  
  15.     var listitemenumerator = listitems.getEnumerator();  
  16.     while (listitemenumerator.moveNext()) {  
  17.         var item = listitemenumerator.get_current().get_item('Title'); // replace with your column name//  
  18.         tasks.push(item);  
  19.         var itemvalue = listitemenumerator.get_current().get_item('Duration'); // replace with your column name//  
  20.         hours.push(itemvalue);  
  21.     }  
  22. }  
  23.   
  24. function failure() {  
  25.     alert("request failed" + args.get_message());  
  26. }   

It is a straightforward implementation to fetch the list items from the list. We are saving this JavaScript file and uploading it to site assets library from which we can refer this file to the main HTML file.

Main HTML  

  1. <html>  
  2.   
  3. <head>  
  4.     <meta http-equiv='cache-control' content='no-cache'>  
  5.     <meta http-equiv='expires' content='0'>  
  6.     <meta http-equiv='pragma' content='no-cache'>  
  7.     <script src="test.js"></script>  
  8.     <!—replace with your path where js file is located in sharepoint!>  
  9.     <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>  
  10.     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
  11.     <script type="text/javascript">  
  12.         $(document).ready(function() {  
  13.             google.charts.load('current', {  
  14.                 'packages': ['corechart']  
  15.             });  
  16.             google.charts.setOnLoadCallback(drawChart);  
  17.         });  
  18.   
  19.         function drawChart() {  
  20.             var data = new google.visualization.DataTable();  
  21.             data.addColumn('string''Task');  
  22.             data.addColumn('number''Hours Per Day');  
  23.             if (hours.length > 1) {  
  24.                 data.addRows(hours.length);  
  25.                 for (var i = 0; i <= hours.length - 1; i++) {  
  26.                     data.setCell(i, 0, tasks[i]);  
  27.                     data.setCell(i, 1, hours[i]);  
  28.                 }  
  29.             }  
  30.             var options = {  
  31.                 title: 'My Daily Activities'  
  32.             };  
  33.             var chart = new google.visualization.PieChart(document.getElementById('piechart'));  
  34.             chart.draw(data, options);  
  35.         }  
  36.     </script>  
  37. </head>  
  38.   
  39. <body>  
  40.     <div id="piechart" style="width: 900px; height: 500px"></div>  
  41. </body>  
  42.   
  43. </html>   

Here in JavaScript code given above, we are setting the data, which we obtained from the referenced JavaScript file.

The code given above is used in content editor Web part to generate the Pie Chart and the final result would be as shown below.

Pie Chart shows casing my daily activities