I get the error "google is not defined", from my google script that creates a table using google.visualization.
How do you add a reference to a google script, and if I get it to run in scripts will I also have to add it to my google site? I'll put my script below.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
function doGet() {
drawTable()
}
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time');
data.addRows(1);
data.setCell(0, 0, 'John');
data.setCell(0, 1, 10000, '$10,000');
data.setCell(0, 2, true);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true});
google.visualization.events.addListener(table, 'select', function() {
var row = table.getSelection()[0].row;
alert('You selected ' + data.getValue(row, 0));
});
}
Apps Script uses JavaScript as it's server side code. Originally, JavaScript was designed as a language to run in the browser (on the users computer). JavaScript in an HTML file, won't run the JavaScript on Google's servers.
In the script editor, you can create two types of files:
Script
HTML
doGet() can only be used in a .gs script file. You can't use it in HTML JavaScript.
Your Code.gs file should have some code that looks like this:
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};
Then you need an HTML file.
index.html
<div id="EntireSite">
<div>
body
<?!= include('Chart'); ?>
<br><br><br><br><br><br><br><br><br><br><br>
</div>
<div>
My Footer
</div>
<div style="background: brown">
<br>
<br>
<br>
<br>
</div>
</div>
In this example, you need a second HTML file for the chart:
Chart.html
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333', ],
['Silver', 10.49, 'silver'],
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ]
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
bar: {groupWidth: '95%'},
legend: 'none',
};
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
chart.draw(data, options);
}
</script>
<div id='chart_div'></div>
Firstly, it seems that you are missing <script> tags around the JavaScript functions that follow the reference to the google.com/jsapi.
Also you need to call the following function to load the appropriate "package".
google.load('visualization', '1.0', {'packages':['table']});
And this function to call drawTable()
google.setOnLoadCallback(drawTable);
Assuming that you are embedding the script within a HTML page, the complete page would look something like:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the table package.
google.load('visualization', '1.0', {'packages':['table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time');
data.addRows(1);
data.setCell(0, 0, 'John');
data.setCell(0, 1, 10000, '$10,000');
data.setCell(0, 2, true);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true});
google.visualization.events.addListener(table, 'select', function() {
var row = table.getSelection()[0].row;
alert('You selected ' + data.getValue(row, 0));
});
}
</script>
</head>
<body>
<div id="table_div"></div>
</body>
</html>
My answer is based on documentation found here: https://developers.google.com/chart/interactive/docs/gallery/table
Related
I want to use google charts and added the following code to a page
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawLines);
function drawLines() {
data = new google.visualization.DataTable();
...
}
The chart is built as expected, but I cannot find out how to add or remove rows when outside the callback-function drawlines()
I tried defining the variable data in different ways:
on toplevel:
var data; // gives me "data is not a function" when used after the callback
google.charts.load('current', {packages: ['corechart', 'line']});
data = new google.visualization.DataTable(); // also gives me "data is not a function"
after the callback-code
var data = new google.visualization.LineChart(document.getElementById('chart_div'));
data.addRow([30,100,95]);
in the callback
I removed keyword var to make data a global var
Nothing worked. Help is very much appreciated!
defining data, chart, & options globally should work fine.
just be sure not to use them until after the callback has fired.
see following working snippet,
click the update chart button to see it work...
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawLines);
var data;
var options;
var chart;
function drawLines() {
data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y0')
data.addColumn('number', 'y1')
data.addRows([
[0, 10, 30],
[1, 11, 31],
[2, 12, 32],
[3, 13, 33],
[4, 14, 34]
]);
options = {
title: 'Test Update'
};
chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
document.getElementById('update-chart').addEventListener('click', updateChart);
}
function updateChart() {
var rangeY0 = data.getColumnRange(1);
var rangeY1 = data.getColumnRange(2);
data.addRow([
data.getNumberOfRows(),
rangeY0.max + 1,
rangeY1.max + 1
]);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<input id="update-chart" type="button" value="Update Chart" />
<div id="chart_div"></div>
In my home.scala.html page's head I have a comprehensive javascript to call a google chart, using a map passed from scala using the java play framework.
<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(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'xVariable');
data.addColumn('number', 'yVariable');
var mapVariable = #mapFromScala;
console.log("Hello world");
for (var mapKey in mapVariable) {
data.addRows([
[new Date(mapKey) , mapVariable[mapKey]]
]);
}
var options = {
chart: {
title: 'This is my map',
subtitle: 'it has a subtitle'
},
width: 1000,
height: 600
};
var chart = new google.charts.Line(document.getElementById('chartId'));
chart.draw(data, options);
}
</script>
and in body
<div id="chartId"></div>
Why don't I get anything back? Even the 'Hello world' console.log doesn't seem to show in SBT console.
The map variable must be brought in as a String. JSON can be used for this but
var mapVariable = "#mapFromScala"
Also works, although the process to convert from String back into a Map is inelegant.
This process is described here, except the data types are different and
data.addRows([[xVariable, yVariable]])
is invoked instead of
jsArray.xVariable = yVariable;
I want to integrate google chart in my laravel5.0 application. The data is in mysql database. As far I've done researching over internet is given bellow
controller part
public function index(){
$barChart= DB::table('clients')
->select('clients.ClientName','clients.Price')
->get();
$bar = json_encode($barChart);
return view('home')
->with('bar', $bar);
}
If I print $bar , the result is
[{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}]
view part
<div class="panel-body" id="barChart"> </div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$bar?>);
var options = {
title: 'My Bar chart',
is3D: 'true'
};
var chart = new google.visualization.PieChart(document.getElementById('barChart'));
chart.draw(data, options);
}
But it shows "table has no column" . I know I haven't create any column and I also understand that simply writing this google.visualization.DataTable(<?=$bar?>) will not create any column. I've tried many ways to create column but can not find any solution. How can I create data table from this?
I also tried chartWraper
<script type="text/javascript">
google.load('visualization', '1.0');
function drawInventoryChart() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [], //don't know how to put $bar here
option: {title: 'test'}
});
wrapper.draw('barChart');
}
google.setOnLoadCallback(drawInventoryChart);
</script>
This also does not work as I can not properly have the value of dataTable[] .
you can use array.forEach to load the data into the data table.
see following example...
google.charts.load('current', {
callback: function () {
// use the following
//var sqlData = <?=$bar?>;
// for example
var sqlData = [
{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}
];
// create data table
var data = new google.visualization.DataTable();
data.addColumn('string', 'Client');
data.addColumn('number', 'Price');
// load data table
sqlData.forEach(function(row) {
data.addRow([row.ClientName, row.Price]);
});
var chart = new google.visualization.BarChart(document.getElementById('barChart'));
chart.draw(data, {
title: 'My Bar chart',
is3D: 'true'
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barChart"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var completed=parseInt(document.getElementById('completed1').value);
var notcompleted=parseInt(document.getElementById('notcompleted1').value);
alert(completed);
alert(notcompleted);
var data = google.visualization.arrayToDataTable([
['Task', 'Student'],
['Students Completed', completed],
['Students Not Completed', notcompleted],
]);
var options = {
title: ''
};
var chart = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data, options);
}
</script>
this script is on my one page i am calling this page multiple times so in console it shows "Google Charts loader.js can only be loaded once."
Move it to whatever file you use to preload all your other global functions etc.
example, i have mine the app.js (using angular)
I'm using the following Script:
<header>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</header>
<body>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
<div id="area_chart_google" class="area-chart"></div>
<body>
I cannot use the script inside Header because I'm using dynamic content.
I figure it out to work when I first load the page, and after refreshing it. My problem now is that I'm using a select menu with an onchange event, similar to this:
<select id="form_frame1" name="frame1" onchange="getChart(this);">
<option value="area_chart_google" >Area Chart</option>
<option value="area_chart_2" selected="selected">Stacked Chart</option>
</select>
My getChart function is:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
}
}
So, once my area_chart_google is not displayed (display: none) and I select it, I get the error:
*Firebug* google-visualization-errors-all-1
*Chrome* Cannot read property 'length' of null
*Safari* 'null' is not an object
I guess is something with getElementById, so I tried using:
window.onload = function(){ javascript code here }
And also:
$(document).ready(function() {
javascript code here
});
Nothing happen. I get no error but the Chart don't appear.
Any help will be highly appreciated.
This is working for me:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
drawChart(); //call this function when using this Google Chart
}
}
You need to load the Google API first:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
You also should have proper <body> and <head> tags in your script.
Otherwise the code is fine. The below works fine for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="area_chart_google" class="area-chart"></div>
</body>
</html>
not sure, but try doing :
google.load("visualization", "1", {packages:["corechart"]});
//..your drawChart() function code here
$(document).ready(function() {
google.setOnLoadCallback(drawChart);
});
I hope you have already included following script in your header:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>