Google Charts: Problem handling a 'click' event - javascript

I have a Google Chart, a bar chart, that I recently extended so that selecting one of the bars will open a new page, showing the data corresponding to that bar. I used the guidelines for basic interactivity, using a selectHandler to process the event.
I then decided to do the same thing when clicking on one of the labels, but I have not been able to get this to work. I looked pretty carefully at the docs, and at this older question (which is, in fact, my actual question: how do I make a hyperlink out of the chart's labels?) for guidance. I added a Listener for click events, and a handler for this, but my chart is not responding to them.
My basic setup is:
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2018-07', 5, 98.0],
['2018-08', 5, 100.0], // etc.
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
alert('The user has clicked on ' + e.targetID);
}
var chart = new google.charts.Bar(document.getElementById('bookgraph_material'));
google.visualization.events.addListener(chart, 'click', clickHandler);
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
The selectHandler works fine. But I can't even get the clickHandler to show the alert (after this works, I'll actually code the rest of it); it's apparently never fired, regardless of where I click. What am I doing wrong?
I set up a JS Fiddle page for this, to experiment with, with an HTML frame so it'll actually work; this shows the working select (albeit to a 404, of course) and the nonworking click.
Thanks.

the 'click' event is not supported by Material charts,
see issue #: 2257...
and there are several configuration options that are not supported as well,
see issue #: 2143...
Material = google.charts.Bar -- packages: ['bar']
Classic = google.visualization.BarChart -- packages: ['corechart']
one work around would be to use a Classic chart with option --> theme: 'material'
or register your own click event,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2016-01', 3, 45.0],
['2016-02', 3, 56.0],
['2016-03', 1, 23.0],
['2016-04', 4, 60.0],
['2016-05', 1, 0],
['2016-06', 3, 14.0],
['2016-07', 4, 65.0],
['2016-08', 1, 15.0],
['2016-09', 13, 234.0],
['2016-10', 20, 834.0],
['2016-11', 5, 115.0],
['2016-12', 5, 58.0],
['2017-01', 6, 122.0],
['2017-02', 4, 84.0],
['2017-03', 1, 0],
['2017-04', 1, 30.0],
['2017-05', 2, 38.0],
['2017-06', 1, 11.0],
['2017-07', 0, 0],
['2017-08', 4, 88.0],
['2017-09', 5, 89.0],
['2017-10', 4, 73.0],
['2017-11', 5, 79.0],
['2017-12', 2, 37.0],
['2018-01', 1, 22.0],
['2018-02', 5, 98.0],
['2018-03', 5, 132.0],
['2018-04', 3, 56.0],
['2018-05', 14, 272.0],
['2018-06', 4, 88.0],
['2018-07', 5, 98.0],
['2018-08', 5, 100.0],
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
if (e.target.tagName === 'text') {
console.log(e.target.textContent);
}
}
var container = document.getElementById('bookgraph_material');
var chart = new google.charts.Bar(container);
google.visualization.events.addListener(chart, 'select', selectHandler);
container.addEventListener('click', clickHandler);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="bookgraph_material"></div>

Related

How to place an icon inside Google ColumnChart

I have columnchart bar which has one column and I wanna place an icon top of the bar.This bar is dynamically changing as randomly.I checked some sources on the internet and Google Chart API but couldn't find a solution.Is there any way to do that?Below you can see the code belongs to my chart
Here it's demo to give you idea about my Grid and Chart also
https://stackblitz.com/edit/angular-pt2kha?file=app/grid-list-overview-example.html
Here what I expect to see
What I tried below to generate this Column Chart below
TS File
title= 'Temperature';
type = 'ColumnChart';
data= [['',25]];
columnNames= ['Element', 'Temperature'];
options= {
backgroundColor: '#fafafa',
legend: {position: 'none'},
animation: {
duration: 250,
easing: 'ease-in-out',
startup: true,
},
bar: {
groupWidth: 50
},
hAxis: {
baselineColor: 'none',
ticks: []
},
vAxis: {
baselineColor: 'none',
ticks: [],
viewWindow: {
max:40,
min:0
}
}
}
width=100;
height=300;
ngOnInit()
{
interval(2000).subscribe(()=>{
this.data = [
['', (Math.random() * 41)],
];
});
}
HTML File
<div style="border-style:solid;border-width:1px;">
<google-chart #chart
[title]="title"
[type]="type"
[data]="data"
[columnNames]="columnNames"
[options]="options"
[width]="width"
[height]="height"
>
</google-chart>
</div>
you can add icons using chart methods getChartLayoutInterface() & getBoundingBox()
on the chart's 'ready' event, find the position of the bar,
then place the image.
although not angular, it will work the same,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Y');
data.addRows([
[{v: 'a', p: {thumb: 'clone_old.png'}}, 20],
[{v: 'b', p: {thumb: 'boba_fett.png'}}, 15],
[{v: 'c', p: {thumb: 'jango_fett.png'}}, 30],
[{v: 'd', p: {thumb: 'clone_3.png'}}, 5],
[{v: 'e', p: {thumb: 'clone_2.png'}}, 25]
]);
var options = {
legend: 'none'
};
var container = document.getElementById('chart_div');
var containerBounds = container.getBoundingClientRect();
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var barBounds = chartLayout.getBoundingBox('bar#0#' + i);
var path = 'http://findicons.com/files/icons/512/star_wars/32/';
var thumb = container.appendChild(document.createElement('img'));
thumb.src = path + data.getProperty(i, 0, 'thumb');
thumb.style.position = 'absolute';
thumb.style.top = (barBounds.top + containerBounds.top - 40) + 'px';
thumb.style.left = (barBounds.left + containerBounds.left + (barBounds.width / 2) - 16) + 'px';
}
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
`

Hierarchies graphs in google charts

How can I build something like this (with subcategories on the one of the axis)
although the requested layout is not available via standard configuration options,
it is possible to achieve, if you're ok with modifying the svg manually
when the chart's 'ready' event fires, add the category labels and group lines
see following working snippet, which is just an example to show the possibility
several assumptions are made based on the size and placement of the chart...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['State', 'Store', 'Sales'],
['California', 'Donald\'s Market', 1560],
['California', 'Alexei\'s Specialties', 1090],
['California', '24-Seven', 345],
['Texas', 'Albert Market', 245],
['Texas', 'Jim\'s Market', 245],
['Texas', 'International Food Store', 82]
]);
var options = {
bars: 'horizontal',
chartArea: {
left: 204
},
height: 400,
vAxis: {
textStyle: {
fontSize: 10
}
}
};
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);
var view = new google.visualization.DataView(data);
view.setColumns([1, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}]);
google.visualization.events.addListener(chart, 'ready', function () {
var rowIndex = -1;
var stateValue = '';
var svgParent = chartDiv.getElementsByTagName('svg')[0];
Array.prototype.forEach.call(chartDiv.getElementsByTagName('text'), function(text) {
var groupLabel;
if ((text.getAttribute('text-anchor') === 'end') &&
(parseFloat(text.getAttribute('x')) < 200)) {
rowIndex++;
if (stateValue !== data.getValue(rowIndex, 0)) {
stateValue = data.getValue(rowIndex, 0);
groupLabel = text.cloneNode(true);
groupLabel.setAttribute('x', '60');
groupLabel.innerHTML = stateValue;
svgParent.appendChild(groupLabel);
addGroupLine(groupLabel, -24);
}
if (rowIndex === (data.getNumberOfRows() - 1)) {
addGroupLine(text, 16);
}
}
});
function addGroupLine(text, yOffset) {
var groupLine = chartDiv.getElementsByTagName('rect')[0].cloneNode(true);
groupLine.setAttribute('y', parseFloat(text.getAttribute('y')) + yOffset);
groupLine.setAttribute('x', '16');
groupLine.setAttribute('height', '0.8');
groupLine.setAttribute('width', '188');
groupLine.setAttribute('stroke', 'none');
groupLine.setAttribute('stroke-width', '0');
groupLine.setAttribute('fill', '#000000');
svgParent.appendChild(groupLine);
}
});
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Annotationchart - Rebase index=100 upon Rangechange

I have an Google Annotation Chart to show relative performance of different investments. User should be able compare performance over a selected time frame, that is, the series values should be rebased / indexed to 100 at the startdate of the visible range of the chart once the timeframe is changed.
Other packages like Amcharts offer a "comparable" function, so have been looking for options like "scaleColumns" and "scaleType" in Google Docs and in other questions here, not finding any clue on how to do this.
Is there any feature I can use and might have missed, or what would be the best approach to recalculate the DataTable with index=100 upon "rangechange".
Code and screenshot is below:
google.charts.load('current', {
packages: ['corechart', 'line', 'table','annotationchart']
});
google.charts.setOnLoadCallback(drawChart);
// ---------- Chart ---------------------------- //
function drawChart() {
//data query
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Gw67zHpKyEd1nu_V698yqYqNgE0x21_ZE_QDHJmsgtE/gviz/tq?gid=803335131&headers=1&range=A1:n451');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: 'Development of the choosen Portfolio since 2008',
legend: {
textStyle : { fontSize: 8 },
maxLines : 2,
position: 'top'
},
width: '30%',
height: 700,
lineWidth: 1,
hAxis: {
format: 'M/d/yy',
title: 'Time'
},
vAxis: {
scaleType: 'log',
title: 'Return (log scale)'
},
//theme: 'maximized',
chartArea:{
left:0,
top:20,
width:'30%',
height:'85%'
},
series: {
22: {
lineWidth: 3,
color: 'red'
}
}
};
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'))
chart.draw(data, options);
}
google.visualization.events.addListener(chart, 'rangechange', rangechange_handler);
function rangechange_handler(e) {
console.log('You changed the range to ', e['start'], ' and ', e['end']);
// How to recalculate datatable to keep index=100 for all series upon rangechange?
}
Update:
There is a way, working on it: https://groups.google.com/forum/#!searchin/google-visualization-api/compare$20zoom|sort:relevance/google-visualization-api/8HjybllsufY/z5uak6AymLcJ
After an extended period of pain got it working, hope it helps somebody: https://jsfiddle.net/AlexHorn/a9z15syr/
var viewColumns = [0];
var colors = [];
for (var i = 0; i < columnIndices.length; i++) {
viewColumns.push({
label: data.getColumnLabel(columnIndices[i]),
type: 'number',
calc: (function(x) {
// use a closure here to lock the value of i to each column
return function(dt, row) {
// return the value normalized to the first row in the view
return dt.getValue(row, columnIndices[x]) / dt.getValue(0, columnIndices[x]);
};
})(i)
});
}

How to reload data in Google Charts Calendar while keeping selected cell?

I use jQuery and I use the following JS function to load and reload / redraw the Google Chart Calendar.
It works, however, it also removes the border from the selected item. I want to reload the calendar data, while keeping the currently selected item selected.
Any ideas?
function refreshCalendar( rows)
{
//if( calendar != 0 )
{
calendar = new google.visualization.Calendar(document.getElementById('calendar_basic'))
google.visualization.events.addListener(calendar, 'select', calendarSelectHandler);
calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows( rows );
calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
}
}
Normally, you would use chart.getSelection and chart.setSelection.
Get selection on 'select' event
Set selection on 'ready' event
getSelection works fine, but setSelection doesn't work with the Calendar chart.
No error is thrown, but nothing is selected.
I tried versions '41' thru 'current'...
To demonstrate, the following example uses both a Calendar chart and a Column chart.
Make a selection on both charts, then click "Redraw Chart".
The selection for the Column chart remains but not on the Calendar.
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionCal) {
calendar.setSelection(selectionCal);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />
I can also confirm that the setSelection() method doesn't change anything on the UI for the calendar chart.
So I looked up what happens after selecting a day in the chart with the mouse. Then I implemented a simple DOM manipulation logic which does the same. You can use that logic as a replacement of the setSelection() use case. (It is just a quick prototype, but I hope it helps you, too).
For a litte demo I adjusted #WhiteHat snippet / the selected day survives now the refresh action (doesn't work with charts which needs to display more than one year!):
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionDate;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
selectionDate = new Date(selectionCal[0].date);
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionDate) {
// google calendar setSelection BUG :/
// https://stackoverflow.com/a/36093217/810944
// do it manually
var doy = selectionDate.getDOY();
markDayInChart(doy);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
function markDayInChart(dayOfYear) {
// clones the logic for clicking / selecting a day via mouse
// keep in mind to clean up the adjusted and added `rect`-elements if you do not use full page reloads!
// doesn't work with charts which needs to display more than one year!
var days_all_svg_group = $('#calendar svg').children('g')[1];
var days_marked_svg_group = $('#calendar svg').children('g')[4];
var day_svg_rect = $('rect:nth-of-type('+dayOfYear+')',$(days_all_svg_group));
// hide the original rect
$(day_svg_rect).css('display: none;');
// add a cloned rect with a different stroke
var day_marked_svg_rect = $(day_svg_rect).clone();
$(day_marked_svg_rect).attr({stroke: '#000000', 'stroke-width': 2});
$(day_marked_svg_rect).attr('stroke-opacity', null);
$(days_marked_svg_group).append(day_marked_svg_rect);
}
// https://stackoverflow.com/a/26426761/810944
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if((year & 3) != 0) return false;
return ((year % 100) != 0 || (year % 400) == 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
};
<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="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />

Not able to click on label in google chart api

I am new to javascript and i am using google chart api for creating charts. i wanted to click on left side label that shows in below image. so, my question is that can we click on left side label?
give me some idea for this. if it is possible then help me.
function drawStackedChart(reqCategoryId,fcategoryName)
{
$.ajax({
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-complaint-result-for-other-category?categoryId="+reqCategoryId,
datatype: "json",
success : function(jsonData)
{
var data = new google.visualization.DataTable();
// Add columns
data.addColumn('string','categoryName');
data.addColumn({type: 'number',role: 'interval'});
var complaintStatus = jsonData[0].complaintStatus;
for(var i=0;i<complaintStatus.length;i++)
{
data.addColumn('number',complaintStatus[i].statusName);
data.addColumn({type: 'number',role: 'scope'});
}
data.addRows(jsonData.length);
var maxVal=jsonData[0].totalCountComplaint;
for(i=0;i<jsonData.length;i++)
{
// trying to create hyperlink
data.setCell(i,0,'+jsonData[i].categoryName+');
data.setCell(i,1,jsonData[i].categoryId);
for(j=0; j< jsonData[i].complaintStatus.length; j++)
{
data.setCell(i,parseInt(jsonData[i].complaintStatus[j].statusId)*2, jsonData[i].complaintStatus[j].countComplaint);
data.setCell(i,parseInt(jsonData[i].complaintStatus[j].statusId)*2+1, jsonData[i].complaintStatus[j].statusId);
}
if(jsonData[i].totalCountComplaint>maxVal)
maxVal=jsonData[i].totalCountComplaint;
}
var options = {
title : fcategoryName+' Complaints Dashboard',
titleTextStyle : {
fontName : 'Arial',
fontSize : 18,
bold : true,
},
isStacked:true,
chartArea: {width:'50%',height:'75%'},
bar: {groupWidth: '50%'},
tooltip : {
isHtml : true,
textStyle : {
fontName : 'sans-serif',
fontSize : 14,
bold : false
}
},
hAxis:{
title:'status values',
gridlines : {
count : maxVal+1
},
baseline:maxVal,//static
},
vAxis:{
title:'Complaint\'s categories',
textStyle : {
fontName : 'sans-serif',
fontSize : 18,
bold : false,
},
},
};
var chart = new google.visualization.BarChart(document.getElementById('donutchart'));
chart.draw(data, options);
new google.visualization.events.addListener(chart, 'select', selectionHandler);
function selectionHandler() {
// code for selection handler
}
you can use the targetID of the 'click' event to find the label that was clicked
when a y-axis label is clicked, the targetID will hold a value similar to the following...
vAxis#0#label#0
you can use the string method split, to find the label value in the data
selection = e.targetID.split('#');
when the first value = vAxis, this means a y-axis label was clicked
if (selection[0].indexOf('vAxis') > -1) {
the first integer refers to the y-axis, in this example, there is only one
the second integer refers to the row in the data
to get the value clicked...
data.getValue(rowIndex, colIndex);
e.g.
data.getValue(parseInt(selection[selection.length - 1]), parseInt(selection[1])));
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' } ],
['Copper', 8.94, '#b87333'],
['Silver', 10.49, 'silver'],
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2']
]);
var options = {
title: 'Density of Precious Metals, in g/cm^3',
width: 600,
height: 400,
bar: {groupWidth: '95%'},
legend: { position: 'none' },
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'click', function(e) {
var selection;
if (e.targetID) {
selection = e.targetID.split('#');
if (selection[0].indexOf('vAxis') > -1) {
console.log('label clicked = ' + data.getValue(parseInt(selection[selection.length - 1]), parseInt(selection[1])));
}
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Categories

Resources