Memory leak in google line charts - javascript

I have been doing lot research on this memory leak in Google charts library. Didnt found any thing thats helping my situation. Not sure whats the updates on this one so far. I saw google chart dev team is trying to fix it and release a new updates.
I'm using line chart and the data is coming from websockets. which is constantly updating.
Thanks in advance
P.S below is the code I use to getting data from websockets. when the socket is connected the drawChart function is called every second. Meaning the whole line chart is redrawn
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'data');
data.addColumn('number', 'date');
var data_test = new google.visualization.DataTable();
data_test.addColumn('string', 'data test');
data_test.addColumn('number', 'date test');
for(var i=0; i<valueArr.length; i+=2) {
if (i>=120) {
data.removeRow(0);
valueArr.splice(0, 2);
timeArr.splice(0, 2);
}
data.addRow([timeArr[i], valueArr[i]]);
}
for(var i=1; i<valueArr.length; i+=2) {
if (i>=120) {
data_test.removeRow(0);
valueArr.splice(0, 2);
timeArr.splice(0, 2);
}
data_test.addRow([timeArr[i], valueArr[i]]);
}
//console.log(valueArr);
// use a DataView to 0-out all the values in the data set for the initial draw
var view = new google.visualization.DataView(data);
var view_test = new google.visualization.DataView(data_test);
// Create and draw the plot
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
var chart_test = new google.visualization.LineChart(document.getElementById('visualization_test'));
var options = {
title:" ",
width: 960,
height: 460,
bar: { groupWidth: "40%" },
legend: { position: "bottom" },
animation: {"startup": true},
curveType: 'function',
lineWidth: 3,
backgroundColor: '#f9f9f9',
colors: ['red'],
tooltip: {
textStyle: {
color: 'red',
italic: true
},
showColorCode: true
},
animation: {
startup: true,
easing: 'inAndOut',
//duration: 500
},
vAxis: {
title: '',
gridlines: {
count: 8,
color: '#999'
}
/*minValue: 1.3,
maxValue: 1.4*/
},
hAxis: {
title: 'Time Stamp'
},
};
//stay in sockets
var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runOnce);
chart.draw(data, options);
chart_test.draw(data, options);
});
chart.draw(view, options);
chart_test.draw(view_test, options);
}
function init() {
try {
socket = new WebSocket(portal);
//console.log('WebSocket status '+socket.readyState);
socket.onopen = function(msg) {
//console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
parseData(msg);
drawVisualization();
};
socket.onclose = function(msg) {
console.log("Disconnected - status "+this.readyState);
};
}
catch(ex){
console.log(ex);
}
}

beginning with drawing only one chart, you might setup similar to following snippet...
this should draw the same chart with new data, only after the previous draw has finished...
function init() {
var getData = true;
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'ready', function () {
getData = true;
});
var options = {
title:" ",
width: 960,
height: 460,
bar: { groupWidth: "40%" },
legend: { position: "bottom" },
animation: {"startup": true},
curveType: 'function',
lineWidth: 3,
backgroundColor: '#f9f9f9',
colors: ['red'],
tooltip: {
textStyle: {
color: 'red',
italic: true
},
showColorCode: true
},
animation: {
startup: true,
easing: 'inAndOut',
//duration: 500
},
vAxis: {
title: '',
gridlines: {
count: 8,
color: '#999'
}
/*minValue: 1.3,
maxValue: 1.4*/
},
hAxis: {
title: 'Time Stamp'
},
};
// if you want data from previous draws, declare here...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
// or see below...
// msg = object with arrays from parseData
function drawVisualization(msg) {
// if you ** don't ** want data from previous draws, declare here instead...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
// ---<
for (var i = 0; i < msg.valueArr.length; i++) {
data.addRow([msg.timeArr[i], msg.valueArr[i]]);
}
chart.draw(data, options);
}
function parseData(msg) {
//... declare timeArr & valueArr locally here
return {
timeArr: timeArr,
valueArr: valueArr
};
}
function startData() {
try {
socket = new WebSocket(portal);
//console.log('WebSocket status '+socket.readyState);
socket.onopen = function(msg) {
//console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
if (getData) {
getData = false;
// pass object with arrays from parseData
drawVisualization(parseData(msg));
}
};
socket.onclose = function(msg) {
//console.log("Disconnected - status "+this.readyState);
};
}
catch(ex){
console.log(ex);
}
}
startData();
}

Related

Google Visualization highlight single grid line

how can I highlight a single grid line? I would like to set an optical temperature limit at 35 ° C.
Thanks! I have now added it to my code, but it does not work .... do you see my mistake? Or did I not understand something in your explanation?
Here is the edited version :
//Google Chart
google.charts.load('current', {
callback: function drawChart(peanut) {
const div = document.createElement('div');
div.id = peanut.color + peanut.mac.split(':').join('');
$('#charts').appendChild(div);
peanut.data = new google.visualization.DataTable();
peanut.data.addColumn('datetime', 'Time');
peanut.data.addColumn('number', '🥜 ' + peanut.label);
for (var i = 0, len = localStorage.length; i < len; i++) {
let dateTime = new Date(parseInt(localStorage.key(i)));
let item = JSON.parse(localStorage.getItem(localStorage.key(i)));
if (item.peanutMac === peanut.mac) {
if (item.temperatureCelsius) {
let temperature = parseFloat(item.temperatureCelsius);
peanut.data.addRows([ [dateTime, temperature] ]);
} else if (item.alert) {
let data = parseInt(item.alert);
peanut.data.addRows([ [dateTime, data] ]);
}
}
}
if (peanut.type == 'thermo') {
peanut.chart = new google.visualization.LineChart($('#' + div.id));
peanut.chartOptions = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
colors: [peanut.rgbColor],
width: document.body.clientWidth,
height: (window.innerHeight - 224) / 2,
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [15.00, 20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
peanut.viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
peanut.viewColumns.push(colIndex);
});
peanut.viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
}
peanut.view = new google.visualiation.DataView(data);
peanut.view.setColumns(viewColumns);
if (peanut.data.getNumberOfRows()) {
peanut.chart.draw(peanut.view, peanut.chartOptions);
}
}
packages:['corechart', 'table']
});
add another series with the value set to 35 for all rows
here, a data view is used to add a calculated column for the optical temperature limit
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y0');
data.addColumn('number', 'y1');
data.addColumn('number', 'y2');
data.addRows([
[1, 32.8, 20.8, 21.8],
[2, 30.9, 29.5, 32.4],
[3, 25.4, 27, 25.7],
[4, 21.7, 28.8, 20.5],
[5, 21.9, 27.6, 20.4]
]);
var options = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
var viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
viewColumns.push(colIndex);
});
viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
var chart = new google.visualization.LineChart($('#chart').get(0));
chart.draw(view, options);
},
packages:['corechart', 'table']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
Its not the best and safest way but I didnt find something on the google documentation:
You could use Jquery for it Ive tried it on the example from google docs and it works click
var line = $("svg g line")[4]
$(line).attr('stroke','red');
A simple way is to set the vAxis baseline to the value you want, say 35, and change the baselineColor. There is no option to change the width of this line, however, so if you need that, you should follow the suggestion above to add a series just to draw this line, and set its lineWidth.

Annotation Google Chart API

i'm trying to use Google Chart API for building an Waterfall chart. I noticed that Candlestick/Waterfall charts are not supporting the annotations.
See this jsfiddle sample
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'MinimumLevel');
data.addColumn('number', 'MinimumLevel1');
data.addColumn('number', 'MaximumLevel');
data.addColumn('number', 'MaximumLevel1');
data.addColumn({type: 'number', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type: 'number', role: 'annotation'});
data.addRow(['Category 1', 0 , 0, 5, 5, 5,'gray',5]);
data.addRow(['Category 2', 5 , 5, 10, 10, 10,'red',10]);
data.addRow(['Category 3', 10 , 10, 15, 15, 15,'blue',15]);
data.addRow(['Category 4', 15 , 15, 10, 10, 10,'yellow',10]);
data.addRow(['Category 5', 10 , 10, 5, 5, 5,'gray',5]);
var options = {
legend: 'none',
bar: { groupWidth: '60%' } // Remove space between bars.
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I would like to put the value of the 5th column at the top of every candlestick.
It should look like this :
Is there a way to do this?
Thanks
I add annotations to candlestick charts by adding annotations to a hidden scatter plot. You can set exactly where you want the annotations to sit by changing the plot.
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Low');
data.addColumn('number', 'Open');
data.addColumn('number', 'Close');
data.addColumn('number', 'High');
data.addColumn('number'); //scatter plot for annotations
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
var high, low, open, close = 160;
for (var i = 0; i < 10; i++) {
open = close;
close += ~~(Math.random() * 10) * Math.pow(-1, ~~(Math.random() * 2));
high = Math.max(open, close) + ~~(Math.random() * 10);
low = Math.min(open, close) - ~~(Math.random() * 10);
annotation = '$' + close;
annotation_text = 'Close price: $' + close;
data.addRow([new Date(2014, 0, i + 1), low, open, close, high, high, annotation, annotation_text]);
}
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
explorer: {},
chartArea: {
left: '7%',
width: '70%'
},
series: {
0: {
color: 'black',
type: 'candlesticks',
},
1: {
type: 'scatter',
pointSize: 0,
targetAxisIndex: 0,
},
},
candlestick: {
color: '#a52714',
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
});
}
<script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
just so happens, i ran into the same problem this week
so I added my own annotations, during the 'animationfinish' event
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var dataChart = new google.visualization.DataTable({"cols":[{"label":"Category","type":"string"},{"label":"Bottom 1","type":"number"},{"label":"Bottom 2","type":"number"},{"label":"Top 1","type":"number"},{"label":"Top 2","type":"number"},{"role":"style","type":"string","p":{"role":"style"}}],"rows":[{"c":[{"v":"Budget"},{"v":0},{"v":0},{"v":22707893.613},{"v":22707893.613},{"v":"#007fff"}]},{"c":[{"v":"Contract Labor"},{"v":22707893.613},{"v":22707893.613},{"v":22534350.429},{"v":22534350.429},{"v":"#1e8449"}]},{"c":[{"v":"Contract Non Labor"},{"v":22534350.429},{"v":22534350.429},{"v":22930956.493},{"v":22930956.493},{"v":"#922b21"}]},{"c":[{"v":"Materials and Equipment"},{"v":22930956.493},{"v":22930956.493},{"v":22800059.612},{"v":22800059.612},{"v":"#1e8449"}]},{"c":[{"v":"Other"},{"v":22800059.612},{"v":22800059.612},{"v":21993391.103},{"v":21993391.103},{"v":"#1e8449"}]},{"c":[{"v":"Labor"},{"v":21993391.103},{"v":21993391.103},{"v":21546003.177999996},{"v":21546003.177999996},{"v":"#1e8449"}]},{"c":[{"v":"Travel"},{"v":21546003.177999996},{"v":21546003.177999996},{"v":21533258.930999994},{"v":21533258.930999994},{"v":"#1e8449"}]},{"c":[{"v":"Training"},{"v":21533258.930999994},{"v":21533258.930999994},{"v":21550964.529999994},{"v":21550964.529999994},{"v":"#922b21"}]},{"c":[{"v":"Actual"},{"v":0},{"v":0},{"v":21550964.52999999},{"v":21550964.52999999},{"v":"#007fff"}]}]});
var waterFallChart = new google.visualization.ChartWrapper({
chartType: 'CandlestickChart',
containerId: 'chart_div',
dataTable: dataChart,
options: {
animation: {
duration: 1500,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'transparent',
bar: {
groupWidth: '85%'
},
chartArea: {
backgroundColor: 'transparent',
height: 210,
left: 60,
top: 24,
width: '100%'
},
hAxis: {
slantedText: false,
textStyle: {
color: '#616161',
fontSize: 9
}
},
height: 272,
legend: 'none',
tooltip: {
isHtml: true,
trigger: 'both'
},
vAxis: {
format: 'short',
gridlines: {
count: -1
},
textStyle: {
color: '#616161'
},
viewWindow: {
max: 24000000,
min: 16000000
}
},
width: '100%'
}
});
google.visualization.events.addOneTimeListener(waterFallChart, 'ready', function () {
google.visualization.events.addListener(waterFallChart.getChart(), 'animationfinish', function () {
var annotation;
var chartLayout;
var container;
var numberFormatShort;
var positionY;
var positionX;
var rowBalance;
var rowBottom;
var rowFormattedValue;
var rowIndex;
var rowTop;
var rowValue;
var rowWidth;
container = document.getElementById(waterFallChart.getContainerId());
chartLayout = waterFallChart.getChart().getChartLayoutInterface();
numberFormatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
rowIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
switch (rect.getAttribute('fill')) {
// use colors to identify bars
case '#922b21':
case '#1e8449':
case '#007fff':
rowWidth = parseFloat(rect.getAttribute('width'));
if (rowWidth > 2) {
rowBottom = waterFallChart.getDataTable().getValue(rowIndex, 1);
rowTop = waterFallChart.getDataTable().getValue(rowIndex, 3);
rowValue = rowTop - rowBottom;
rowBalance = Math.max(rowBottom, rowTop);
positionY = chartLayout.getYLocation(rowBalance) - 6;
positionX = parseFloat(rect.getAttribute('x'));
rowFormattedValue = numberFormatShort.formatValue(rowValue);
if (rowValue < 0) {
rowFormattedValue = rowFormattedValue.replace('-', '');
rowFormattedValue = '(' + rowFormattedValue + ')';
}
annotation = container.getElementsByTagName('svg')[0].appendChild(container.getElementsByTagName('text')[0].cloneNode(true));
$(annotation).text(rowFormattedValue);
annotation.setAttribute('x', (positionX + (rowWidth / 2)));
annotation.setAttribute('y', positionY);
annotation.setAttribute('font-weight', 'bold');
rowIndex++;
}
break;
}
});
});
});
$(window).resize(function() {
waterFallChart.draw();
});
waterFallChart.draw();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Event click from google chart blocks pop-ups when I try to open a new window

An event click from a Google chart blocks pop-ups when I try to open a new window.
This is how I draw the chart:
printChart: function() {
var self = this;
google.load('visualization', '1', {
'packages': ['corechart'],
"callback": function() {
try {
showLoading('widget');
var data = google.visualization.arrayToDataTable([]);
data.addColumn('string', 'Classification');
data.addColumn('number', $.t('columnVisits'));
data.addColumn('number', $.t('columnContacted'));
data.addColumn('number', $.t('columnUnattended'));
data.addColumn('number', '');
data.addColumn({ type: 'string', role: 'annotation' });
//We add all the elements to the graph
var dataClassified = self.getClassifiedFromConfig();
_.each(dataClassified, function(element) {
var inactive = (element.Inactive <= 0 && element.Visits <= 0 && element.ActivitiesPhoneCalls <= 0) ? 1 : element.Inactive,
assigned = element.Assigned > 0 ? element.Assigned : 1;
data.addRow([
{
v: element.IdClassification.toString(),
f: element.Classification
},
element.Visits/assigned,
element.ActivitiesPhoneCalls/assigned,
inactive/assigned,
0, //empty column for placing the Cycle as an annotation at the end of the stacked bars.
element.Cycle + ' ' + $.t('days')
]);
});
var options = {
isStacked: true,
hAxis: {
format: '#%',
minValue: 0,
maxValue: 1,
textStyle: {
color: '#404040',
fontName: 'Roboto',
fontSize: 14
}
},
vAxis: {
textStyle: {
color: '#404040',
fontName: 'Roboto',
fontSize: responsiveFontSize
}
},
bar: {
groupWidth: '75%'
},
annotations: {
alwaysOutside: true,
stemColor: 'none', // eliminate the tick for the annotation
textStyle: {
fontName: 'Roboto',
fontSize: 14,
bold: false,
italic: false,
color: '#404040'
}
},
series: {
3: {
visibleInLegend: false
}
},
legend: {
position: 'top'
},
tooltip: {
trigger: 'none'
},
height: responsiveHeight,
width: '100%',
colors: ['#85ac1f', '#fccd3d', '#eaeaea'],
enableInteractivity: true
};
var chart = new google.visualization.BarChart(document.getElementById('portfolio-coverage-chart'));
google.visualization.events.addListener(chart, 'onmouseover', function(e){
self.mouseOverHandler(chart, data);
});
google.visualization.events.addListener(chart, 'select', function(e){
self.selectHandler(chart, data);
});
/*$('.portfolio-coverage-chart').on('click', function() {
self.selectHandler(chart, data);
});*/
chart.draw(data, options);
} catch (e) {
console.log("error printChart " + e);
} finally {
hideLoading('widget');
}
}
});
},
When the user clicks in a bar of my Google chart I call this event:
google.visualization.events.addListener(chart, 'select', function(e){
self.selectHandler(chart, data);
});
The "selectHandler" function:
selectHandler: function(chart, data) {
var self = this;
var id = 5;
var customView = "";
var elementClick = chart.getSelection();
if (elementClick.length > 0){
var row = elementClick[0].row,
column = elementClick[0].column;
if (column === 1) {
id = 5;
customView = "customview.visitcompanies";
} else if (column === 2) {
id = 6;
customView = "customview.contactcompanies";
} else if (column === 3) {
id = 7;
customView = "customview.unattendedcompanies";
} else {
return;
}
//nulls out the selection so we can select it again
chart.setSelection();
var idClassification = parseInt(data.getValue(row, 0));
var params = self.setParams(idClassification);
doDrilldown(id, customView, "companies", params);
}
}
And then, the "doDrillDown" method try to open a new window applying the window.open function:
// open entity page
var newTab = window.open(url, '_blank');
if (newTab) {
newTab.focus();
} else {
alert('Please allow popups for this website');
}
But the pop-ups of my website get blocked before opening a new window.
If instead of the event handler from google I call an on click event works as expected (the problem here is that the data from "chart.getSelection();" is not update, and I get the selection done before the last one):
$('.portfolio-coverage-chart').on('click', function() {
self.selectHandler(chart, data);
});
Why is this happening?

is not a function within the class

I am working on a small class to handle Google Chart and for some odd reason I keep getting
googleChart.js:86 Uncaught TypeError: this.swapChart is not a function
On the page I have a button with id "btnSwitch", click on which triggers a switch of the chart from chart view to the table view and vice-versa. This is defined within this.addChartSwitchListener() and called within this.init_chart()
I can call this.swapChart() within init method so I have to assume that issue is with:
_button.addEventListener('click', this.switchChart, false);
Here is my code below:
google.load('visualization', '1.0', {'packages': ['charteditor', 'controls']});
//google.setOnLoadCallback(drawDashboard);
var GChart = GChart || (function () {
var _graphType;
var _minTime;
var _maxTime;
var _hAxisTitle;
var _vAxisTitle;
var _tableData;
var _data;
var _dashboard;
var _lineChart;
var _button;
var _showChart;
return {
init: function (tableData, graphType, minTime, maxTime, hAxisTitle, vAxisTitle) {
// google charts
//_google = google;
_tableData = tableData;
// load chart params
_graphType = graphType;
_minTime = minTime;
_maxTime = maxTime;
_hAxisTitle = hAxisTitle;
_vAxisTitle = vAxisTitle;
// some other initialising
this.build_googlechart();
},
build_googlechart: function ()
{
this.init_chart();
// also tried this - with the same result.
// google.load('visualization', '1.0', {'packages':['corechart'], 'callback': this.drawChart});
},
init_chart: function ()
{
// var data = new google.visualization.DataTable();
_data = new google.visualization.DataTable(_tableData);
// Create a dashboard.
_dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
if (_graphType === 'LineChart') {
this.lineChart();
} else {
this.columnChart();
}
this.addChartSwitchListener();
},
addChartSwitchListener: function ()
{
_button = document.getElementById('btnSwitch');
_button.addEventListener('click', this.switchChart, false);
_showChart = "Chart";
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(_lineChart, 'ready', function () {
if (_showChart !== 'Table') {
$('.save_chart').show();
$('.save_chart').removeClass('disabled');
$('.save_chart').attr('href', _lineChart.getChart().getImageURI());
$('#filter_div').show();
} else {
$('.save_chart').hide();
$('#filter_div').hide();
}
});
},
swapChart: function ()
{
var chart = "Table";
if (_showChart === "Chart") {
chart = _graphType;
}
_lineChart.setChartType(chart);
_lineChart.setOptions(this.getOptions(_showChart));
_lineChart.draw();
},
switchChart: function ()
{
_showChart = _button.value;
this.swapChart();
_showChart = (_showChart === 'Table') ? 'Chart' : 'Table';
_button.value = _showChart;
},
getOptions: function (chartType)
{
var options;
switch (chartType) {
case 'Chart':
options = {
backgroundColor: {
fill: 'transparent'
},
legend: 'right',
pointSize: 5,
crosshair: {
trigger: 'both'
},
hAxis: {
},
vAxis: {
}
};
break;
case 'Table':
options = {
showRowNumber: true,
width: '100%',
height: '100%'
};
break;
default:
options = {};
}
return options;
},
lineChart: function ()
{
var lineChartRangeFilter = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'filter_div',
'options': {
filterColumnIndex: 0,
ui: {
chartType: 'LineChart',
chartOptions: {
backgroundColor: {fill: 'transparent'},
height: '50',
chartArea: {
width: '90%'
}
}
}
}
});
// Create a pie chart, passing some options
_lineChart = new google.visualization.ChartWrapper({
'chartType': "LineChart",
'containerId': 'chart_div',
'options': {
backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
viewWindow: {
min: _minTime,
max: _maxTime
},
},
vAxis: {
title: _vAxisTitle
}
}
});
// Establish dependencies, declaring that 'filter' drives 'pieChart',
// so that the pie chart will only display entries that are let through
// given the chosen slider range.
_dashboard.bind(lineChartRangeFilter, _lineChart);
// Draw the dashboard.
_dashboard.draw(_data);
},
columnChart: function () {
_lineChart = new google.visualization.ChartWrapper({
'chartType': "ColumnChart",
'containerId': 'chart_div',
'dataTable': _data,
'options': {backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
},
vAxis: {
title: _vAxisTitle,
}
}
});
_lineChart.draw();
}
};
}());
This is because you pass a reference to that method to addEventListener, which will later be called with the window object as context, and not your this object.
To overrule this behaviour, you can use several solutions, but here is one with bind():
_button.addEventListener('click', this.switchChart.bind(this), false);

Google chart api explorer vs. selecthandler

I have problem with using Google.charts api... i have chart drawing function like this:
function columnDraw(sectionname) {
var data = google.visualization.arrayToDataTable(array);
var view = new google.visualization.DataView(data);
var options = {
title: "Activity of users",
bar: {groupWidth: "100%"},
legend: {position: "top"},
height: 300,
// explorer: {
//maxZoomOut:0
//maxZoomIn: 50,
// keepInBounds: true,
// axis: 'horizontal'
// },
hAxis: {
title: 'Amount of activity',
minValue : 0,
format: '0'
},
vAxis: {
title: 'Amount of users',
minValue : 0,
format: '0'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById(sectionname));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
document.getElementById("input0").value = data.getValue(selectedItem.row, 0);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(view, options);
}
I want to choose parts of chartcolumn by cklicing on them, but i have a problem with zooming. This code works but once I uncomment the explorer part, selectHandler function wont work properly. Can anyone tell me whats wrong with it?
You're missing a ","
maxZoomOut:0,

Categories