When my chart animates to display new data, the labels on the columns disappear and are not rendered again. All the the data is being imported correctly and displayed on the columns. The label data is only displayed on the initial render of the chart.
The success handler returns 'values', an array of three numbers, for example: [10, 8, 2] and is working correctly.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="genderChart" style="overflow: hidden"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(initChart);
var chart;
var options = {
legend: {position: "none"},
chartArea: {width:'100%'},
animation: {duration: 1000, easing: 'out'}
};
function initChart() {
chart = new google.visualization.ColumnChart(document.getElementById('genderChart'));
drawGenderChart();
}
function drawGenderChart() {
google.script.run.withSuccessHandler(function (values){
genderData = values;
}).getGenderData();
label00 = JSON.stringify(genderData[0]);
label01 = JSON.stringify(genderData[1]);
label02 = JSON.stringify(genderData[2]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'Students');
data.addColumn({role: 'style'});
data.addColumn({role: 'annotation'});
data.addRows([
['Male', genderData[0], '#9fc5e8', label00],
['Female', genderData[1], '#d5a6bd', label01],
['Non-binary', genderData[2], '#b7b7b7', label02]
]);
chart.draw(data, options);
}
setInterval(drawGenderChart, 1000);
</script>
</body>
</html>
Apps Script:
function getGenderData() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Console");
var range = sheet.getRange("A3:C4");
var values = range.getValues();
return values.flat();
}
CodePudding user response:
google.script.run
runs asynchronously, so you need to wait for it to finish,
before drawing the chart.
to accomplish, simply place the rest of the code within the success handler...
google.script.run.withSuccessHandler(function (values){
genderData = values;
label00 = JSON.stringify(genderData[0]);
label01 = JSON.stringify(genderData[1]);
label02 = JSON.stringify(genderData[2]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'Students');
data.addColumn({role: 'style'});
data.addColumn({role: 'annotation'});
data.addRows([
['Male', genderData[0], '#9fc5e8', label00],
['Female', genderData[1], '#d5a6bd', label01],
['Non-binary', genderData[2], '#b7b7b7', label02]
]);
chart.draw(data, options);
}).getGenderData();