multiple google charts with separate options - javascript

I'm starting out with google charts (gauges)
i need to put multiple gauges on the same page, each with a different max value (which is set in options)
but what it seems is that the options is somehow global for all charts
they all become 0 to 1
here's my code
<script type="text/javascript">
google.charts.load('current', { 'packages': ['gauge'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.getJSON("Dashboard/GaugeData", function (jsn) {
var dGauges = $('#gauges');
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
$.each(jsn, function (i, item) {
data.addRow([item.Label, item.Pending]);
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, {
width: 400, height: 400,
redFrom: 90, redTo: 100,
yellowFrom: 75, yellowTo: 90,
minorTicks: 5, max: item.Max
});
});
});
} setInterval(function () {
drawChart();
}, 10000);
</script>
please note that i cannot prepare a new div for each chart, since the amount of charts is dynamic (from json)
i believe i could create the divs dynamically and then check before each refresh if i need to add the div or remove etc... but i'm hoping there's a better way

Related

How to get data from firebase and display on my google gauge chart

I tried to get data from firebase to display on gauge chart but it's doesn't show anything and shown error "Uncaught (in promise)
Here's my js code.
<script type="text/JavaScript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var database = firebase.database();
var Temperature;
database.ref().on("value", function(snap){
Temperature= snap.val().Temperature;
});
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', Temperature]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Data is loaded from Firebase asynchronously, since it may take some time. While this is happening, your main code will continue to run. Then once the data is available, your callback is called.
This means that right now, your chart.draw(data, options) runs before the Temperature= snap.val().Temperature has been executed. That explains why you don't see any data in your chart.
The solution is always the same: any code that needs the data from the database, needs to be inside the callback, or be called from there. So in your case, the simplest fix is:
function drawChart() {
var database = firebase.database();
var Temperature;
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
database.ref().on("value", function(snap){
Temperature= snap.val().Temperature;
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', Temperature]
]);
chart.draw(data, options);
});
}
Also see:
Why Does Firebase Lose Reference outside the once() Function?

Updating data of charts already instantiated

I am using the Google Charts and i need to update a map that is already instantiated as a map worth actually want when you click the refresh button the data inside of a map.
Today I am doing in the following way:
var dataGraf = google.visualization.arrayToDataTable(parsVal);
var chart = document.getElementById('curve_chart');
chart.draw(dataGraf);
But nothing happens. For i instantiate my map i used the following commands:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(parsVal);
var options = {
title: 'Membros x Visitantes',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
How can i do to update, just when I click the button. Remembering that my 'ataGraf' has my array with the new values.
I did a JsFiddle to illustrate my problem.
first...
google.charts.load & setOnLoadCallback should only be called once per page load
you can also include the callback in the load statement
next, by saving a reference to the original chart, you can animate from one dataset to another
on the button click, create data and call draw
also recommend not adding event handlers directly in html tags
see following working snippet, the data is "swapped" on each button click...
google.charts.load('current', {
callback: function () {
// draw first chart
var data = google.visualization.arrayToDataTable([
['Data', 'Membros', 'Visitantes'],
['1', 4, 6],
['2', 5, 7]
]);
var options = {
animation: {
startup: true,
duration: 1200,
easing: 'linear'
},
title: 'Membros x Visitantes',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
// draw same chart with new data on button click
var newData = null;
document.getElementById('chart_button').addEventListener('click', drawNewChart, false);
function drawNewChart() {
// switch between newData and data on each click
if (newData === null) {
newData = google.visualization.arrayToDataTable([
['Data', 'Membros', 'Visitantes'],
['1', 9, 2],
['2', 1, 7]
]);
chart.draw(newData, options);
} else {
chart.draw(data, options);
newData = null;
}
}
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<button id="chart_button">Atualizar gráficos</button>
<div id="curve_chart"></div>

Google charts tooltip with pie chart isn't shown

Im using google chart to drow pie chart. I need to change slice offset value slice onhover event. I wrote some code but the problem is chart does not display tooltip.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
var options = {
is3D: true,
tooltip: { textStyle: { color: '#000000' }, showColorCode: true }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandlerOver(e) {
//alert('selectHandlerOver');
var row = e.row;
var s = $.parseJSON('{ ' +
'"is3D": "true",' +
'"slices": { "' + row + '": { "offset": "0.2" } },' +
'"animation": { "duration": "100", "easing": "out"}' +
'}')
chart.draw(data, s);
}
function selectHandlerOut(e) {
//alert('selectHandlerOut');
var row = e.row;
var s = $.parseJSON('{"is3D": "true", "slices": { "' + row + '": { "offset": "0.0" } } }')
chart.draw(data, s);
}
google.visualization.events.addListener(chart, 'onmouseover', selectHandlerOver);
google.visualization.events.addListener(chart, 'onmouseout', selectHandlerOut);
chart.draw(data, options);
}
I think this is because O override onmouseover event with custom behaviour. Any suggestions?
This is not because you have overridden the mouse over event. This is because you are calling chart.draw() inside it. Draw method cancels out any tooltips which rendered for the previous.
If you want fine-grained control, You are better off using something like jQueryUI to show your tooltips.

Google visualization gauge in vertical alignment

I want to put google gauge in vertical alignment. This is my javascript code (it's copy paste from google playground)
<script type='text/javascript'>
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 80],
['CPU', 55],
['Network', 68]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('menu2'));
chart.draw(data, options);
}
</script>
And this is my html div
<div id="menu2"></div>
and css
#menu2
{
background-color:#FFD700;
height:570px;
width:150px;
float:right;
}
any idea?
I just added inline style to div in which gauge will load. Ans removed all width height options from script given my google.
Here is the fiddle: http://jsfiddle.net/NB3Eg/
You can play with its html & css here https://code.google.com/apis/ajax/playground/?type=visualization#gauge

Google Visualization Animation when chart loads for the first time

I would like to know if I can apply an animation to the charts on the first time it draws?
And not only when a change of data happens?
THanks!
UPDATED ANSWER
Google has updated chart options and added the option to animate the chart on the first time it draws.
So the only thing you have to do is psecify it in the options like that:
var options = {
animation: {
duration: 1500,
startup: true //This is the new option
}
};
So you dont have to load an empty chart on the beggining or to do any other hack.
DEMO
The Chart should be rendered before you can apply your animation which is showing transition from one state to another. You can either change the data or change the chart options to create the transition and its animation.
To be able to show animation on the first time, you can simply create an empty (no data) chart, and then add your data to the chart, to show the data animation.
var options = {
animation:{
duration: 1000,
easing: 'out',
}
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
var chart = new google.visualization.ColumnChart...
chart.draw(data, options);
// Adding data
data.addRow(['V', 200]);
Try something like this http://jsfiddle.net/h7mSQ/163/. The way to do this is to render chart with zero values and then set values as required and draw chart again. Don't forget to set minimal and maximal value for (in this example) vertical axis.
function drawChart() {
var option = {title:"Yearly Coffee Consumption in our company",
width:600, height:400,
animation: {duration: 1000, easing: 'out',},
vAxis: {title: "Cups of coffee", minValue:0, maxValue:500},
hAxis: {title: "Year"}};
var data = new google.visualization.DataTable();
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
data.addRow(['2003', 0]);
data.addRow(['2004', 0]);
data.addRow(['2005', 0]);
// Create and draw the visualization.
var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(data, option);
data.setValue(0, 1, 400);
data.setValue(1, 1, 300);
data.setValue(2, 1, 400);
chart.draw(data, option);
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

Categories

Resources