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;
Related
Whenever I run my app from the flask server locally on my own machine then my google chart shows up and looks great. However, when I log onto my own server and try running my app from there nothing show's up.
I have looked at the console and it does not show any errors and furthermore shows the space where the google chart should go but it is blank.
This is my code to create the chart. This is using the flask template inheritance model.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var course = '{{ myFun }}';
course = course.split(' ');
var putInTable = new Array();
for (var i = 0; i < course.length; i++){
putInTable.push(course[i].split(":"));
}
putInTable.pop();
for (var i = 0; i < putInTable.length; i++){
putInTable[i][1] = parseFloat(putInTable[i][1]);
}
putInTable.unshift(["courseName", "overlap"]);
var data = google.visualization.arrayToDataTable(putInTable);
var options = {title: "Visualization of Overlap"};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
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 have a View called "historicos.ejs". In the 1st load, the page only has 2 date pickers to make a range query, submit button and chart(google charts) in blank. I need to make the query and pass the data after the 2nd render(after pressing submit) into the chart.
This is the script tag placed in the head of my view
<script type="text/javascript">
// his with query data from the server
var histo = his;
console.log(histo)
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'X');
data.addColumn('number', 'Temperatura (C)');
data.addRows();
var options = {
width: 550,
height: 363,
title: 'Comportamiento de la Temperatura',
hAxis: {
title: 'Tiempo desde '
},
vAxis: {
title: 'Temperatura'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('tem_line'));
chart.draw(data, options);
}
</script>
The console.log() command in the second line show an empty array or undefined in the browser console.
This is the "historicos.ejs" controller
app.get('/historicos', function(req, res) {
res.render("historicos.ejs")
});
app.post('/historicos/buscar', function(req, res) {
//...some query.... query return "his" variable with the data
res.render("historicos.ejs", {
his:JSON.stringity(his)
})
});
NOTE: I tested my code without the stringify and showed it in the view with ejs <% %> and it works perfectly.
When I press the submit button, the console.log in the script does not show anything even if the data has the stringify data.
NOTE2: I tried res.json(JSON.stringify(his) and it works perfectly, it shows in the browser all the data from mongodb.
So my question is, what can I do to pass the variable into my script to plot the data into the chart?
A simple solution would be to wrap the json in a script tag with type application/json. This will prevent the script from actually running and allow you to use the DOM to query the text content and parse it.
<script id="histo-data" type="application/json">
<%= his %>
</script>
<script type="text/javascript">
var data = document.getElementById('histo-data').textContent.trim()
if(data){
var histo = JSON.parse(data);
console.log(histo)
google.load('visualization', '1', {packages: ['corechart']})
// ...
Here's a quick demo showing this works for some static JSON: http://jsfiddle.net/grnp8n9n/
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