Reputation: 1548
I have 3 google charts which are identical apart from the data and id of the chart. At the moment I call these charts like this.
google.charts.setOnLoadCallback(drawBasic);
google.charts.setOnLoadCallback(drawBasic2);
google.charts.setOnLoadCallback(drawBasic3);
Because the charts are almost identical I would like one function instead of 3, as I like to use less code if possible, but when I do this it doesn't work. google.charts.setOnLoadCallback(drawBasic(mydata,myid));
If I could send the data like this, then I wouldn't need 3 functions, I would only need one drawBasic function, with different data every time it is called. I won't paste all 3 functions I will just paste the one function to show how my function is laid out.
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Month');
data.addColumn('number', 'Sales');
data.addRows([
[new Date(2016, 4), 0],[new Date(2016, 5), 0],[new Date(2016, 6), 0],[new Date(2016, 7), 0],[new Date(2016, 8), 0],[new Date(2016, 9), 0]
]);
var options = {
title: 'Total Sales Last Six Months',
hAxis: {
title: 'Sales'
},
vAxis: {
title: 'Month'
},
backgroundColor: { fill:'transparent' },
legend: {position: 'none'},
'animation':{duration:1000,easing:'out'}
};
var chart = new google.visualization.BarChart(document.getElementById('total_sales_chart'));
chart.draw(data, options);
setTimeout(function(){
data.setValue(0,1,14690);
data.setValue(1,1,2785);
data.setValue(2,1,23345);
data.setValue(3,1,10345);
data.setValue(4,1,12456);
data.setValue(5,1,19642);
chart.draw(data, options);
},1000);
}
So is it possible for me to send my data to the function. I am new to google charts, but where possible I don't like using 3 functions when I can get away with only one.
Upvotes: 2
Views: 720
Reputation: 61222
setOnLoadCallback
is meant to be used once per page load
however, you can add the callback
to the load
statement
then call the draw function from there...
google.charts.load('current', {
callback: function () {
drawBasic(mydata1, myid1);
drawBasic(mydata2, myid2);
function drawBasic(data, id) {
...
}
},
packages: ['corechart']
});
Upvotes: 1
Reputation: 138267
Do sth like:
var data=[[1,2],[3,4]];
google.charts.setOnLoadCallback(function(){
for(i=0;i<data.length;i++){
drawBasic(data[i]);
}
});
This small function calls drawBasic with one array element as arguments list. So your drawBasic function will be called like this:
drawBasic([1,2]);
drawBasic([3,4]);
Upvotes: 0