Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google charts - run function after draw

working with google charts, trying to get a value from the chart after it is done drawing, I understand I need to make a callback function that will run after 'draw' is complete - but I can't get it to work... Where do I call the function "afterDraw" to make it run after function "draw" is complete? Please help.. Thanks :)

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addColumn('number', 'Stam');
data.addRows([
  ['Mushrooms', 3,5],
  ['Onions', 1,7],
  ['Olives', 1,3],
  ['Zucchini', 1,5],
  ['Pepperoni', 2,8]
]);

var options = {'title':'How Much Pizza I Ate Last Night',
               'height':500};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);

}
function afterDraw(){
    alert('all done');
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="chart_div"></div>
like image 438
Haksuma Avatar asked Sep 27 '16 08:09

Haksuma


1 Answers

after the chart is created and before it is drawn,

add a listener for the 'ready' event

this will let you know when the chart has been drawn

google.visualization.events.addListener(chart, 'ready', afterDraw);

see following working snippet...

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addColumn('number', 'Stam');
data.addRows([
  ['Mushrooms', 3,5],
  ['Onions', 1,7],
  ['Olives', 1,3],
  ['Zucchini', 1,5],
  ['Pepperoni', 2,8]
]);

var options = {'title':'How Much Pizza I Ate Last Night',
               'height':500};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

google.visualization.events.addListener(chart, 'ready', afterDraw);

chart.draw(data, options);

}
function afterDraw(){
    console.log('all done');
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="chart_div"></div>
like image 105
WhiteHat Avatar answered Oct 16 '22 16:10

WhiteHat