Using Thymeleaf with Google charts and Java Map - javascript

The Thymeleaf block I have made in JavaScript cuts off the ending ; of the variable, and throws an Uncaught (in promise) SyntaxError: Unexpected token ' in JSON at position 2.
The code does parse like it should, except for the data variable. Parsed code:
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = {'Expense1': 25.0, 'Expense2': 20.0, 'Expense3': 40.0};
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: 'Data test',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Pre Thymeleaf code:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = "{ 'cols': [" +
"{'id':'','label':'Expense','pattern':'','type':'string'}" +
"{'id':'','label':'Amount','pattern':'','type':'number'}]," +
"'rows': [";
var data = /*[[${chart.DataPoints}]]*/;
var end = "]}";
var res = jsonData.concat(data);
var res = res.concat(end);
var json = JSON.parse(res);
var data = new google.visualization.DataTable(json);
var options = {
title: /*[[${chart.title}]]*/'',
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
The data var is either like it is right now, or when enclosed in "", it cuts off the closing semi-colon. How do I get Thymeleaf of JavaScript to cast the data var to a string (while maintaining the '' it contains)?

Does this work for you? I don't think you need to build your data as a JSON string first, simply create it as a JavaScript object:
<script type="text/javascript" th:inline="javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var json = {
'cols': [
{'id':'', 'label': 'Expense', 'pattern': '', 'type': 'string'},
{'id':'', 'label': 'Amount', 'pattern': '', 'type': 'number'}
],
rows: []
};
var data = /*[[${chart.DataPoints}]]*/ [];
var rows = [];
Object.keys(data).forEach(function(key) {
rows.push({
"c": [
{"v": key, "f": null},
{"v": data[key], "f": null}
]
});
});
json['rows'] = rows;
var data = new google.visualization.DataTable(json);
var title = /*[[${chart.title}]]*/ '';
var options = {
title: title,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
edit: you can format the data however you want... it's pretty trivial to do in JavaScript.

Related

Converting a Json value from a string to an integer

I am trying to convert a JSON string into an integer so that I can use this data in a google chart. As of right now I can only get one set of data to be displayed in my chart.
Here is my JQUERY code:
$("#shotsandbigcc").click(function(){
//alert("Button works");
$("#shotsandbigcc_popup").toggle();
var integer = $("#shotsandbigcc").attr("name");
//alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {myData: integer},// data to submit
dataType: 'json',
success: function(response){
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMultSeries);
function drawMultSeries() {
var len = response.length;
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable([
['Year', 'Shots on Target', 'Shots off Target'],
[year, ontarget, offtarget],
[year, ontarget, offtarget]
]);
var options = {
title: 'Shooting Accuracy',
chartArea: {width: '50%'},
hAxis: {
title: 'Amount of Shots',
minValue: 0
},
vAxis: {
title: 'Year'
}
};
var chart = new google.visualization.BarChart(document.getElementById('shotsandbigcc_chart'));
chart.draw(data, options);
}
}
});
});
The JSON data is in an array which has this format [{"Year":"2019/2020","Shots_on_Target":"302","Shots_off_Target":"578","Accuracy":"0.34"},{"Year":"2020/2021","Shots_on_Target":"74","Shots_off_Target":"93","Accuracy":"0.44"}]
If someone could tell me how I can display both 2019/2020 and 2020/2021 data to be displayed. I would be most grateful as right now only the 2020/2021 data is being displayed. Thank you.
For integet value part:
var ontarget = parseInt(response[i].Shots_on_Target);
For your data part:
var vizData = [];
vizData.push(['Year', 'Shots on Target', 'Shots off Target']);
for(var i=0; i<len; i++){
var year = response[i].Year;
var ontarget = parseInt(response[i].Shots_on_Target);
var offtarget = parseInt(response[i].Shots_off_Target);
vizData.push([year, ontarget, offtarget]);
alert(ontarget);
}
alert(year);
var data = google.visualization.arrayToDataTable(vizData);
explaination: since in the loop the values are getting updated in every iteration so, the 'year', 'ontarget' and 'offtarget' will have the latest values only. So on every iteration you have to store values so that they do not get overwritten. For that now this code is pushing in array in every iteration preserving the previous values. Which now you can use in the google.visualization function.
Happy Coding!

Live update highcharts-gauge from dweet

I would like to have the gauge chart update live dweet data, which is success.
The problem is that every time a new data is pushed to the array humidityData, a new pointer is added in the gauge chart as shown here:
guage chart Though I'd like to have one live-updating-pointer instead.
Could this be done by pop() the prev data?
<script language="JavaScript">
//Array to store sensor data
var humidityData = []
<!--START-->
$(document).ready(function() {
//My Dweet thing's name
var name = 'dweetThingName'
//Humidity chart
var setupSecondChart = function() {
var chart2 = {
type: 'gauge'
};
var title = {...};
var pane = {...};
var yAxis = {...};
var tooltip = {
formatter: function () {
return '<b>' + "Humidity: " + Highcharts.numberFormat(this.y, 2) + "%";
}
};
//Series_Humidity
humiditySeries = [{
name: 'Humidity %',
data: humidityData,
tooltip: {
valueSuffix: '%'
}
}]
//Json_Humidity
var humJson = {};
humJson.chart = chart2;
humJson.title = title;
humJson.tooltip = tooltip;
humJson.xAxis = xAxis;
humJson.yAxis = yAxis;
humJson.legend = legend;
humJson.exporting = exporting;
humJson.series = humiditySeries;
humJson.plotOptions = plotOptions;
console.log("Sereies: : " +humJson)
//Container_Humidity
$('#containerHumidity').highcharts(humJson);
}
var humiditySeries = [] ....
dweetio.get_all_dweets_for(name, function(err, dweets){
for(theDweet in dweets.reverse())
{
var dweet = dweets[theDweet];
//Dweet's variables' names
val2 = dweet.content["Humidity"]
//Add the vals into created arrayDatas
humidityData.push(val2)
console.log("HumidityData: " + humidityData)
}
//Call other charts
setupSecondChart()
});
When you initialize/update your chart make sure that data array contains only one element. The dial is created for every point in this array (to visualize it on the plot).

Changing the number format in google charts graphs

I have a problem to change number format in my google chart.
I checked stackoverflow topic and I found it : http://jsfiddle.net/h5ea6xqu/
My problem is simple, I want exactly the same thing, but it doesn't working.
I have "," instead space for my grouping symbol... If someone have the solution, it would be awesome.
my problem
My code :
function drawChart($id) {
var id=$id;
var kwexist = (id + "_kw_exist");
var kwexistvariable = $("#"+kwexist).html();
var kwled = (id + "_kw_led");
var kwledvariable = $("#"+kwled).html();
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(kwexistvariable), '#3B7CC9', parseFloat(kwexistvariable)],
['LED kWh', parseFloat(kwledvariable), '#3B7CC9' , parseFloat(kwledvariable)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
})
numberFormat.format(data, 1);
var chart_div = document.getElementById('chart_div_kw');
var chart = new google.visualization.ColumnChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = chart.getImageURI();
var testokok = chart.getImageURI();
console.log(chart_div.innerHTML);
});
chart.draw(data, options);
}
not sure i follow the question exactly
but if you want to format the number shown on the bar (annotation)
also format that column...
numberFormat.format(data, 3);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart($id) {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(10000), '#3B7CC9', parseFloat(10000)],
['LED kWh', parseFloat(15000), '#3B7CC9' , parseFloat(15000)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
});
numberFormat.format(data, 1);
numberFormat.format(data, 3);
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Create a google chart from XML data in a Symfony project

Please I want to know where to put the XML file from where I retrieve data for the chart, in a Symfony project?
I tried to put values directely in the javascript code and that worked, but when I retrieved data from XML to fill the chart, that didn't work and I got this error in the developer console : Failed to load resource
$(document).ready(function(){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var drawChart= setInterval (function drawCharts() {
var xml=new XMLHttpRequest() ;
xml.open("GET", "statFile.xml",true) ;//this is the line that causes the problem
xml.onreadystatechange = function () {
if (xml.readyState == 4) {
var doc=xml.responseXML ;
var root = doc.getElementsByTagName("CHART") ;
////VALUES IN
var paramss= root[0].getElementsByTagName("VALUES_IN");
console.log(paramss) ;
var value_in1=paramss[0].childNodes[1].innerHTML;
var value_in2=paramss[0].childNodes[3].innerHTML;
var value_in3=paramss[0].childNodes[5].innerHTML;
var value_in4=paramss[0].childNodes[7].innerHTML;
var value_in5=paramss[0].childNodes[9].innerHTML;
var value_in6=paramss[0].childNodes[11].innerHTML;
var value_in7=paramss[0].childNodes[13].innerHTML;
var value_in8=paramss[0].childNodes[15].innerHTML;
var value_in9=paramss[0].childNodes[17].innerHTML;
var value_in10=paramss[0].childNodes[19].innerHTML;
var value_in11=paramss[0].childNodes[21].innerHTML;
var value_in12=paramss[0].childNodes[23].innerHTML;
////VALUES OUT
var paramsx= root3[0].getElementsByTagName("VALUES_OUT");
console.log(paramsx) ;
var value_out1=paramsx[0].childNodes[1].innerHTML;
var value_out2=paramsx[0].childNodes[3].innerHTML;
var value_out3=paramsx[0].childNodes[5].innerHTML;
var value_out4=paramsx[0].childNodes[7].innerHTML;
var value_out5=paramsx[0].childNodes[9].innerHTML;
var value_out6=paramsx[0].childNodes[11].innerHTML;
var value_out7=paramsx[0].childNodes[13].innerHTML;
var value_out8=paramsx[0].childNodes[15].innerHTML;
var value_out9=paramsx[0].childNodes[17].innerHTML;
var value_out10=paramsx[0].childNodes[19].innerHTML;
var value_out11=paramsx[0].childNodes[21].innerHTML;
var value_out12=paramsx[0].childNodes[23].innerHTML;
window.value_in1=value_in1;window.value_in2=value_in2;window.value_in3=value_in3;window.value_in4=value_in4;
window.value_in5=value_in5;window.value_in6=value_in6;window.value_in7=value_in7;window.value_in8=value_in8;
window.value_in9=value_in9;window.value_in10=value_in10;window.value_in11=value_in11;window.value_in12=value_in12;
window.value_out1=value_out1;window.value_out2=value_out2;window.value_out3=value_out3;window.value_out4=value_out4;
window.value_out5=value_out5;window.value_out6=value_out6;window.value_out7=value_out7;window.value_out8=value_out8;
window.value_out9=value_out9;window.value_out10=value_out10;window.value_out11=value_out11;window.value_out12=value_out12;
drawChart();
function drawChart(){
var data = google.visualization.arrayToDataTable([
['Mois', 'Frequence'],
[value_in1, parseInt(value_out1)],
[value_in2, parseInt(value_out2)],
[value_in3, parseInt(value_out3)],
[value_in4, parseInt(value_out4)],
[value_in5, parseInt(value_out5)],
[value_in6, parseInt(value_out6)],
[value_in7, parseInt(value_out7)],
[value_in8, parseInt(value_out8)],
[value_in9, parseInt(value_out9)],
[value_in10, parseInt(value_out10)],
[value_in11, parseInt(value_out11)],
[value_in12, parseInt(value_out12)],
]);
/*series: {
2 : { areaOpacity: 10 },
};
*/
var options = {
title: 'Fréquence des visites du site',
curveType: 'function',
legend: { position: 'bottom' },
backgroundColor: {
fill : 'transparent'
}
};
var chart = new google.visualization.AreaChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
} }
xml.send() ;
});
},30000);

Is it possible to create line chart with following csv data

I tried to create line chart using google chart apis and other for following csv data. None of them helped:
csv data looks like this:
"Date,Term,Segment,Visitor"
"2014/01/01,2014/01/01 - 2014/01/31,All visitors,2"
"2014/01/01,2014/01/01 - 2014/01/31,New user,0"
"2014/01/01,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/02,2014/01/01 - 2014/01/31,All visitors,7"
"2014/01/02,2014/01/01 - 2014/01/31,New user,1"
"2014/01/02,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/03,2014/01/01 - 2014/01/31,All visitors,5"
"2014/01/03,2014/01/01 - 2014/01/31,New user,0"
"2014/01/03,2014/01/01 - 2014/01/31,Mobile traffic,0"
"2014/01/04,2014/01/01 - 2014/01/31,All visitors,3"
.............
I faced many issue while using google chart as you can find here:
CSV data loading give Not enough columns given to draw the requested chart
Is it possible to create line chart for this short of data?
Chart should look like this:
--------UPDATED CODE -----------
Why does it not show EVEN dates on X- axix?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("Chart3-data1.csv", function(csvString) {
var transData = [['Date', 'All visitors', 'New user', 'Mobile traffic']];
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
for (var i = 1; i < arrayData.length; i++) {
console.log(arrayData[i][0]);
var fields = arrayData[i][0].split(',');
console.log(fields);
switch ( (i - 1) % 3) {
case 0:
var allVisitors = parseInt(fields[3]);
break;
case 1:
var newUser = parseInt(fields[3]);
break;
case 2:
var mobile = parseInt(fields[3]);
transData.push([ fields[0], allVisitors, newUser, mobile] );
break;
}
}
var data = new google.visualization.arrayToDataTable(transData);
var options =
{
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('gauge'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="gauge" style="width: 900px; height: 500px;"></div>
</body>
</html>
Resulting graph:
I'd change your csv data to:
Date, All visitors, New user, Mobile traffic
2014/01/01, 2, 0, 0
2014/01/02, 7, 1, 0
2014/01/03, 5, 0, 0
2014/01/04, 3, 0, 2
2014/01/05, 4, 1, 2
From those data this chart is produced (no changes in code):
Change of data - one option with JS:
$.get("chart-data-orig.csv", function(csvString) {
var transData = [['Date', 'All visitors', 'New user', 'Mobile traffic']];
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// index 0 is header which will be changed
for (var i = 1; i < arrayData.length; i++) {
console.log(arrayData[i][0]);
var fields = arrayData[i][0].split(',');
console.log(fields);
switch ( (i - 1) % 3) {
case 0:
var allVisitors = parseInt(fields[3]);
break;
case 1:
var newUser = parseInt(fields[3]);
break;
case 2:
var mobile = parseInt(fields[3]);
transData.push([ fields[0], allVisitors, newUser, mobile] );
break;
}
}
var data = new google.visualization.arrayToDataTable(transData);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});

Categories