Add new Data Row in Google Visualisation - javascript

I am trying to making dynamic Google Line chart. I am fetching my datatable from Google Sheet.
I added eventlistener in html to update the data row. So that, existing data row gets updated.
My aim is to delete existing data rows from the chart and new data rows.
Code.gs:
function getTableDataTV(){
//Chart load with this datatable
const ws = SpreadsheetApp.openById("").getSheetByName("Sheet 1"); //2nd worksheet ID
const data = ws.getRange (2,1,ws.getLastRow() -1, 9).getDisplayValues();
return data
}
function getvoddata() {
//new data table for eventlistener
const ss = SpreadsheetApp.openById("");//2nd worksheet ID
const sw = ss.getSheetByName("Sheet 2");
var finaldata = sw.getRange (2,1,sw.getLastRow() -1, 9).getDisplayValues();
return finaldata
}
HTML:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(getData);
var chart;
var options;
function getData(){
google.script.run.withSuccessHandler(drawChart).getTableDataTV();
}
function drawChart(dataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = dataReturned.map(r => [new Date(r[0].slice(6,10),r[0].slice(0,2),r[0].slice(3,5)), parseInt(r[1]),parseInt(r[2]),parseInt(r[3]),parseInt(r[4])]);
data.addRows(newData);
options = {
title: 'Total Views',
subtitle: 'ABP News Vs Competitor Channels'
};
chart = new google.charts.Line(document.getElementById('chart'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
//Update Data Row
document.getElementById("pd1").addEventListener("click",newchart);
function newchart(){
google.script.run.withSuccessHandler(updateChart).getvoddata();
}
function updateChart(newdataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = newdataReturned.map(r => [new Date(r[0].slice(6,10),r[0].slice(0,2),r[0].slice(3,5)), parseInt(r[1]),parseInt(r[2]),parseInt(r[3]),parseInt(r[4])]);
data.addRows(newData);
// redraw the chart.
chart.draw(data, options);
}
</script>
.....
<body>...
<a id="pd1">VOD</a>
<div id="chart" style="width: 1000px; height: 400px"></div>
</body>
I am also getting error on console when add below line:
document.getElementById("pd1").addEventListener("click",newchart);
Error:
Uncaught TypeError: document.getElementById(...) is null
I got this updatefunction from this website and it is working on jsfiddle.
Please check, what I am doing wrong here.
Thank You

In your situation, how about the following modification?
Modified script:
In this modification, your HTML and Javascript are modified. I thought that when I saw your HTML and Javascript, the button is not shown in your HTML, and also, the container for inserting the chart is not shown. And, when I modified your HTML and Javascript by these situations and your sample script shown in your jsfiddle.
<div id="chart"></div>
<button id="pd1">update chart</button>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(getData);
var chart;
var data;
var options;
document.getElementById("pd1").addEventListener("click", newchart);
function getData() {
google.script.run.withSuccessHandler(drawChart).getTableDataTV();
}
function newchart() {
google.script.run.withSuccessHandler(updateChart).getvoddata();
}
function drawChart(dataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = dataReturned.map(r => [new Date(r[0].slice(6, 10), r[0].slice(0, 2), r[0].slice(3, 5)), parseInt(r[1]), parseInt(r[2]), parseInt(r[3]), parseInt(r[4])]);
data.addRows(newData);
options = { title: 'Total Views', subtitle: 'ABP News Vs Competitor Channels' };
chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
function updateChart(newdataReturned) {
data = new google.visualization.DataTable();
data.addColumn('date', 'Days');
data.addColumn('number', 'A');
data.addColumn('number', 'B');
data.addColumn('number', 'C');
data.addColumn('number', 'D');
var newData = newdataReturned.map(r => [new Date(r[0].slice(6, 10), r[0].slice(0, 2), r[0].slice(3, 5)), parseInt(r[1]), parseInt(r[2]), parseInt(r[3]), parseInt(r[4])]);
data.addRows(newData);
chart.draw(data, options);
}
</script>
Note:
In this modification, it supposes that your functions getTableDataTV() and getvoddata() at Google Apps Script return the correct values you expect. Please be careful this.

Related

Create Google line graph from existing array when call IP

I have created a web server on ESP8266 that uses Google gauge to display current temperature data and line graph to display previous data. The gauge and line graph will update as new data come in. Everything works well and when I call the IP the line graph will display and start to populate. The problem is that every IP call the line graph starts with no data and populates all over again because when dataTable is initialized it is returning a new empty data table. Can anyone make a suggestion on creating a line graph from the existing data array in the datatable when make IP call? Thanks.
Code to update line graph:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
//Create opening gauges
var gaugeData = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Room 1', 0],
['Room 2', 0]
]);
var gaugeOptions = {
width: 800, height: 240,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(gaugeData, gaugeOptions);
//Obtain new temperature data and update gauge and line graph
setInterval(updateValues, 3000);
function updateValues() {
//Obtain Room 1 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
Room1temp = parseFloat(this.responseText);
gaugeData.setValue(0, 1, Room1temp);
chart.draw(gaugeData, gaugeOptions);
}
};
xhttp.open("GET", "/Room1temp", true);
xhttp.send();
//Obtain Room 2 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
Room2temp = parseFloat(this.responseText);
gaugeData.setValue(1, 1, Room2temp);
chart.draw(gaugeData, gaugeOptions);
}
};
xhttp.open("GET", "/Room2temp", true);
xhttp.send();
};
//Update Google line chart with timestamp and Room 1 & 2 temperatures
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Room 1');
data.addColumn('number', 'Room 2');
setInterval(updateGraph, 3000);
function updateGraph() {
//create timestamp
let date = new Date();
var Year = date.getFullYear();
var Month = date.getMonth();
var Day = date.getDate();
var Hour = date.getHours();
var Min = date.getMinutes();
var Sec = date.getSeconds();
//Update line graph
if(data.getNumberOfRows()<5){
data.addRows([
[new Date(Year,Month,Day,Hour,Min,Sec), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
} else {
var view = new google.visualization.DataView(data);
data.addRows([
[new Date(Year,Month,Day,Hour,Min,Sec), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
data.removeRow(0);
}
var options = {
title: 'Temperature Data',
pointSize: 8
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}; //End function updateGraph
} // End function drawChart
</script>
</head>
<body>
<div id="chart_div" style="width:600px;margin-left:auto;margin-right:auto"></div>
<div id="curve_chart" style="width:1400px;margin-left:auto;margin-right:auto"></div>
</body>
</html>
try making the IP calls in succession, waiting for each to complete,
before continuing to the next and updating the charts.
see following snippet...
google.charts.load('current', {
packages: ['corechart', 'gauge']
}).then(function () {
//Create opening gauges
var gaugeData = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Room 1', 0],
['Room 2', 0]
]);
var gaugeOptions = {
width: 800, height: 240,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var gaugeChart = new google.visualization.Gauge(document.getElementById('chart_div'));
gaugeChart.draw(gaugeData, gaugeOptions);
// line chart
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Room 1');
data.addColumn('number', 'Room 2');
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
var options = {
title: 'Temperature Data',
pointSize: 8
};
//Obtain new temperature data and update gauge and line graph
setInterval(updateValues, 3000);
function updateValues() {
//Obtain Room 1 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var Room1temp = parseFloat(this.responseText);
gaugeData.setValue(0, 1, Room1temp);
gaugeChart.draw(gaugeData, gaugeOptions);
//Obtain Room 2 temperature and update Google Gauge
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var Room2temp = parseFloat(this.responseText);
gaugeData.setValue(1, 1, Room2temp);
gaugeChart.draw(gaugeData, gaugeOptions);
//Update line graph
if(data.getNumberOfRows()<5){
data.addRows([
[new Date(), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
} else {
data.addRows([
[new Date(), parseFloat(Room1temp), parseFloat(Room2temp)]
]);
data.removeRow(0);
}
chart.draw(data, options);
}
};
xhttp.open("GET", "/Room2temp", true);
xhttp.send();
}
};
xhttp.open("GET", "/Room1temp", true);
xhttp.send();
};
});

How to set export csv option to button in google visualization Pie chart

I am using Google visualization pie chart for showing transaction state.
I want to export to csv, there is functionality ToolBar to export csv,html,iGoogle but I want to specific to csv only without select options.
you can use static method --> dataTableToCsv
google.visualization.dataTableToCsv
this will create a csv string of the data in a data table.
it will not export the column headings, but those can be added manually...
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['A', 10],
['B', 20],
['C', 30],
['D', 40],
['E', 50],
['F', 60]
]);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data);
$('.csv-button').on('click', function () {
var browserIsIE;
var csvColumns;
var csvContent;
var downloadLink;
var fileName;
// build column headings
csvColumns = '';
for (var i = 0; i < data.getNumberOfColumns(); i++) {
csvColumns += data.getColumnLabel(i);
if (i < (data.getNumberOfColumns() - 1)) {
csvColumns += ',';
}
}
csvColumns += '\n';
// build data rows
csvContent = csvColumns + google.visualization.dataTableToCsv(data);
// download file
browserIsIE = false || !!document.documentMode;
fileName = 'data.csv';
if (browserIsIE) {
window.navigator.msSaveBlob(new Blob([csvContent], {type: 'data:text/csv'}), fileName);
} else {
downloadLink = document.createElement('a');
downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
downloadLink.download = fileName;
raiseEvent(downloadLink, 'click');
downloadLink = null;
}
});
function raiseEvent(element, eventType) {
var eventRaised;
if (document.createEvent) {
eventRaised = document.createEvent('MouseEvents');
eventRaised.initEvent(eventType, true, false);
element.dispatchEvent(eventRaised);
} else if (document.createEventObject) {
eventRaised = document.createEventObject();
element.fireEvent('on' + eventType, eventRaised);
}
}
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<div>
<button class="csv-button ui-button ui-widget ui-corner-all">
<span class="ui-icon ui-icon-circle-triangle-s"></span><span> Download CSV</span>
</button>
</div>
<div id="chart_div"></div>
Google will provide you u need to pass your API key inside it
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
var visualization;
function draw() {
drawVisualization();
drawToolbar();
}
function drawVisualization() {
var container = document.getElementById('visualization_div');
visualization = new google.visualization.PieChart(container);
new google.visualization.Query('https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA').
send(queryCallback);
}
function queryCallback(response) {
visualization.draw(response.getDataTable(), {is3D: true});
}
function drawToolbar() {
var components = [{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
};
google.charts.setOnLoadCallback(draw);
</script>
</head>
<body>
<div id="visualization_div" style="width: 270px; height: 200px;"></div>
<div id="toolbar_div"></div>
</body>
</html>
fore more :
https://developers.google.com/chart/interactive/docs/gallery/toolbar

Unable to draw a google chart from firebase db

I want to visualize some simple sensor readings stored in firebase in a basic line graph from Google charts.
The data is structured like this:
KgPdzr3PgDaKVa73asd: {
date: "29/03/201
time: "15:21:07"
value: 21.461541056632996
}
Unfortunately the line graph won't load, and I can't figure out why. The json objects is loaded successfully, so I think it's got something to do with the drawing part of it. Any help in the right direction will be most appreciated.
<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
authDomain: "internet-of-things-62d39.firebaseapp.com",
databaseURL: "https://internet-of-things-62d39.firebaseio.com",
projectId: "internet-of-things-62d39",
storageBucket: "internet-of-things-62d39.appspot.com",
messagingSenderId: "143567304866"
};
firebase.initializeApp(config);
var database = firebase.database();
firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
temps = snapshot.val();
console.log(temps);
google.charts.load('current', {'packages':['corechart','line']});
google.charts.setOnLoadCallback(drawChart(temps));
});
function parse (temp){
return(new Date(temp.replace(/-/g, '/'))).getTime()
}
// google.charts.load('current', {'packages':['corechart', 'line']});
// google.charts.setOnLoadCallback(drawChart);
function drawChart(temps) {
var array = $.map(temps, function(value, index) {
return [value];
});
var data = new google.visualization.DataTable();
data.addColumn('number', 'date');
data.addColumn('number', 'time');
data.addColumn('number', 'value');
var sort = function(a,b){return parse (a.time) - parse(b.time)};
var tempData = array.sort(sort);
var output=[];
for (var i = 0; i<tempData.length;i++){
var item = tempData[i];
output.push([
// parseFloat(parse(item.time)),
parseFloat(item.time),
parseFloat(item.date),
parseFloat(item.value)
]);
}
console.log(output);
data.addRows(output);
var options = {
chart: {
title: 'title',
subtitle: 'subtitle'
},
width: 900,
height: 500
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Added (bold): 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'
Made some minor changes as well. Cheers. Removed some errors by changing jquery version which is loaded.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script>
<script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyBGiHpuzcgw_Ettlko_oU66U-gbW_SbEUA",
authDomain: "internet-of-things-62d39.firebaseapp.com",
databaseURL: "https://internet-of-things-62d39.firebaseio.com",
projectId: "internet-of-things-62d39",
storageBucket: "internet-of-things-62d39.appspot.com",
messagingSenderId: "143567304866"
};
firebase.initializeApp(config);
var database = firebase.database();
firebase.database().ref('/Oslo/temperature').once('value').then(function(snapshot) {
temps = snapshot.val();
console.log(temps);
google.charts.load('current', {
'packages': ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawChart(temps));
});
function parse(temp) {
return (new Date(temp.replace(/-/g, '/'))).getTime()
}
function drawChart(temps) {
var array = $.map(temps, function(value, index) {
return [value];
});
var data = new google.visualization.DataTable();
data.addColumn('number', 'date');
data.addColumn('number', 'time');
data.addColumn('number', 'value');
var sort = function(a, b) {
return parse(a.time) - parse(b.time)
};
var tempData = array.sort(sort);
var output = [];
for (var i = 0; i < tempData.length; i++) {
var item = tempData[i];
output.push([
// parseFloat(parse(item.time)),
parseFloat(item.time),
parseFloat(item.date),
parseFloat(item.value)
]);
}
console.log(output);
data.addRows(output);
var options = {
chart: {
title: 'title',
subtitle: 'subtitle'
},
width: 900,
height: 500
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
console.log("data + options: " + data, options)
chart.draw(data, options);
}
google.charts.load('current', {
'packages': ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawChart);
</script>

Google Charts Dashboard, AJAX call fails to load data from SQL DB

Ive been trying to load data from a SQL table thats generated daily via a SP, Table consists of 4 columns.
My Ajax call gets the data and puts into an array -
Array
Heres my code im using to draw the view and pass the array -
var chartData;
$(document).ready(function () {
$.ajax({
url: "/Reporting/LeaveList",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
//console.log(data);
console.log(typeof data);
chartData = data;
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
google.setOnLoadCallback(createTable);
});
});
function createTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
data.addRow(chartData[0])
// Create a dashboard.
var dash_container = document.getElementById('dashboard_div'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Create a date range slider
var myDateSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_div',
'options': {
'filterColumnLabel': 'Date'
}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div'
});
// Bind myTable to the dashboard, and to the controls
// this will make sure our table is update when our date changes
myDashboard.bind(myDateSlider, myTable);
// Line chart visualization
var myLine = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'line_div',
});
// Bind myLine to the dashboard, and to the controls
myDashboard.bind(myDateSlider, myLine);
myDashboard.draw(data);
And heres some of the controller -
data = (
from u in db.StaffReportingDay
select new StaffReportingDayVM
{
Date = u.Date.ToString(),
AnnualLeave = u.AnnualLeave,
CompassionateLeave = u.CompassionateLeave,
Sick = u.Sick,
StudyLeave = u.StudyLeave,
Total = u.Total
}).ToList();
}
var ChartOne = new object[data.Count + 1];
ChartOne[0] = new object[]
{
"Date",
"Annual Leave",
"Sick Leave",
"Total on Leave"
};
int j = 0;
foreach(var i in data)
{
j++;
ChartOne[j] = new object[] {i.Date.ToString(), i.AnnualLeave, i.Sick, i.Total };
}
return Json(ChartOne, JsonRequestBehavior.AllowGet);
What i cant get is the array to pull into the view, i just get an error -
Uncaught Error: Type mismatch. Value Annual Leave does not match type number in column index 1
Ive tried many things but would like some pointers and other people to give their insight please.
Solved with
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'AnnualLeave');
data.addColumn('number', 'CompassionateLeave');
data.addColumn('number', 'StudyLeave');
data.addColumn('number', 'Sick');
data.addColumn('number', 'Total');
$.each(chartData, function (i, row) {
data.addRow([
(new Date(row.Date)),
parseFloat(row.AnnualLeave),
parseFloat(row.CompassionateLeave),
parseFloat(row.StudyLeave),
parseFloat(row.Sick),
parseFloat(row.Total)
]);
});

Organization Chart from sharepoint list items

I want to create an organization chart which I want to populate using the values from a sharepoint list. I would like to retrieve items using REST and Javascript. Here is my code. It in partially working, but cannot create a chart. Please help someone.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
debugger;
$.ajax({
url: "http://myurl/_api/Web/Lists/GetByTitle('Employee Hierarchy')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (r) {
debugger;
var items = r.d.results;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Entity');
data.addColumn('string', 'ParentEntity');
data.addColumn('string', 'ToolTip');
for (var i = 0; i <items.length; i++) {
var employeeId = r.d[i][0].toString();
var employeeName = r.d[i][1];
var designation = r.d[i][2];
var reportingManager = r.d[i][3] != null ? r.d[i][3].toString() : '';
data.addRows([[{
v: employeeId,
f: employeeName + '<div>(<span>' + designation + '</span>)</div><img src = "Pictures/' + employeeId + '.jpg" />'
}, reportingManager, designation]]);
var chart = new google.visualization.OrgChart($("#chart")[0]);
chart.draw(data, { allowHtml: true });
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart">
</div>
this is the structure of my sharepoint list
The following example demonstrates how to visualize SharePoint List data as organization chart via Google Visualization API
google.load("visualization", "1", { packages: ["orgchart"] });
google.setOnLoadCallback(displayChart);
function displayChart()
{
loadListItems('Employee Hierarchy')
.done(function(data){
var items = data.d.results;
drawChart(items);
})
.fail(function(error){
console.log(error);
});
}
function drawChart(items) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
for (var i = 0; i < items.length; i++) {
data.addRow([items[i]['Title'],items[i]['Manager']['Title'],'']);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
function loadListItems(listTitle){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/items?$select=Title,Manager/Title&$expand=Manager",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
});
}
Key points
In my example the list has the following schema:
Field Name Type
Title Text
Manager Lookup
Description Note
List view page
Resulting page

Categories