Empty GetSelection() Object in Google Charts' Gantt Chart - javascript

I've been learning to use Google Charts for a while and so far, I'm having no problem. However, recently I tried using Gantt Charts and a problem came up. I managed to draw a chart correctly with a data fed by SQL server. However, I want to alert the ID of the selected entity if a chart entity is clicked.
I understand that Google Charts have this getSelection() function and Event Handler. However, when I'm trying to implement that, the array returns empty (just [{}] written in the console). I even used Google Charts' example but it still returns empty array.
Here's the code I use:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task ID');
data.addColumn('string', 'Task Name');
data.addColumn('date', 'Start Date');
data.addColumn('date', 'End Date');
data.addColumn('number', 'Duration');
data.addColumn('number', 'Percent Complete');
data.addColumn('string', 'Dependencies');
data.addRows([
['Research', 'Find sources',
new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null],
['Write', 'Write paper',
null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
['Cite', 'Create bibliography',
null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, 'Research'],
['Complete', 'Hand in paper',
null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
['Outline', 'Outline paper',
null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, 'Research']
]);
var options = {
height: 275
};
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
// When the table is selected, update the orgchart.
google.visualization.events.addListener(chart, 'select', function()
{
var obj = chart.getSelection();
alert(obj[0].column);
});
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Here's the jsfiddle: https://jsfiddle.net/2ku7tzex/1/#&togetherjs=cjVlbdFhV3
Does anybody know where I did wrong?
Thanks before!

This https://jsfiddle.net/hrtgp54r/ resolved the issue for me.
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(){
var selections = chart.getSelection();
if (selections.length == 0)
{
alert('Nothing selected');
}
else
{
var selection = selections[0];
console.info(selection);
alert('You selected ' + (selection.row == null ? 'something' : data.getValue(selection.row, 0)));
}
};

Related

Drawing Google pie by dynamic data

I am trying to draw a simple Google pie chart by creating a dynamic table using JavaScript.
Why my code fails?
var g;
for (g=0; g <3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Failed');
data.addColumn('number', 'Passed');
data.addRows(1);
data.setCell(0, 0, "Work?");
data.setCell(0, 1, 80);
data.setCell(0, 2, 20);
var chartName = 'piechart'+(g+1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data,options);
}
3 pie charts are being drawn on my screen, but they all have one color and one slice, and not 20% 80% like in my code.
Also, I'm not getting any errors on my console.
Are you aiming for something like this?
Also if you can, consider using addRows instead of setCell
I think the problem is with your table / data structure.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart1"></div>
<div id="piechart2"></div>
<div id="piechart3"></div>
<script>
// Load the Visualization API and the corechart package.
google.charts.load('current', {
'packages': ['corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var g;
for (g = 0; g < 3; g++) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'PassOrfail');
data.addColumn('number', 'Percentage');
data.addRows([
['Passed', 80],
['Failed', 20],
]);
var chartName = 'piechart' + (g + 1);
var chart = new google.visualization.PieChart(document.getElementById(chartName));
chart.draw(data);
}
}
</script>

How to change Line Opacity in google charts?

I am using Google Charts and I am able to change the colour of a line half way through a graph conditionally using a dataView, as shown in code below:
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function (data, row) {
var colorDown = '#ff9900';
var colorUp = '#27B291';
var opacity = 'opacity, 0.2;'
var currentdate = new Date();
var givendate = new Date(row.getValue)
if (data.getValue(row, 0) > currentdate) {
return colorDown;
} else {
return colorUp;
}
},
type: 'string',
role: 'style'
}
]);
I was wondering if there is way I can also change the line opacity conditionally as I can't seem to find a way to do it and other methods I have tried do not seem to work? Thanks.
using the style column role, you can combine color and opacity as follows...
'color: #ff9900;opacity: 0.2;'
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.arrayToDataTable([
['x', 'y'],
[new Date(2018, 6, 15), 2924],
[new Date(2018, 6, 16), 2381],
[new Date(2018, 6, 17), 2489],
[new Date(2018, 6, 18), 2235],
[new Date(2018, 6, 19), 2155],
[new Date(2018, 6, 20), 2844],
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function (data, row) {
var colorDown = 'color: #ff9900;';
var colorUp = 'color: #27B291;';
var opacity = 'opacity: 0.2;'
var currentdate = new Date();
var givendate = new Date(row.getValue)
if (data.getValue(row, 0) > currentdate) {
return colorDown + opacity;
} else {
return colorUp + opacity;
}
},
type: 'string',
role: 'style'
}
]);
chart.draw(dataView, {
legend: {
position: 'none'
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Goole Visualization DateRangeFilter Data issue. Data Conflict between Feb and March

When I'm selecting the dates between 1st feb to 28th feb, the Google visualization displaying the data of March instead of February.
Screenshot
The Below code has data and control and chart wrappers.
google.load('visualization', '1', {packages:['corechart','controls','table'], callback:drawChart});
Js Fiddle Link
Please help me in finding a solution for this.
Thanks in advance.
try using the newer library, loader.js vs jsapi
seems to work fine here...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('date','OrderDate');
data.addColumn('number','Order_Qty');
data.addRows([
[new Date(2014,0,1),100],
[new Date(2014,0,3),120],
[new Date(2014,0,30),110],
[new Date(2014,1,1),170],
[new Date(2014,1,10),180],
[new Date(2014,1,25),110],
[new Date(2014,2,1),170],
[new Date(2014,2,14),170],
[new Date(2014,2,20),170],
[new Date(2014,3,12),170],
[new Date(2014,3,16),170],
[new Date(2014,3,13),170]
]);
var table_Chart = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
'options': {},
'view': {'columns':[0, 1]}
});
var slider_Date = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'filter_date_div_Date',
'options': {
'filterColumnIndex':'0'
}
});
new google.visualization.Dashboard(document.getElementById('dashboard_div'))
.bind([slider_Date],[table_Chart])
.draw(data);
},
packages: ['controls', 'table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="filter_date_div_Date"></div>
<div id="table_div"></div>
</div>
This was a bug in the Google charts Date() handling. It is fixed now by its developer.
Github: google/google-visualization-issues Chart data series shows up mis-aligned for all February data
Short term solution for the .clone() and .toDataTable() issue with the live version of the Visualization.
Clone Usage:
prev: newDatatable = oldDatatable.clone();
now: newDatatable = cloneDataTable(oldDatatable);
ToDatatableUsage:
prev: newDatatable = oldDataView.toDatatable();
now: newDatatable = convertDataViewToDataTable(oldDataView);
Functions:
function cloneDataTable(dataTable) {
var newDataTable = dataTable.clone();
for (var c = 0; c < dataTable.getNumberOfColumns(); c++) {
if (dataTable.getColumnType(c) == 'datetime' || dataTable.getColumnType(c) == 'date' ) {
for (var r = 0; r < dataTable.getNumberOfRows() ; r++) {
newDataTable.setValue(r, c, dataTable.getValue(r, c));
}
}
}
return newDataTable;
}
function convertDataViewToDataTable(dataView) {
var newDataTable = dataView.toDataTable();
for (var c = 0; c < dataView.getNumberOfColumns(); c++) {
if (dataView.getColumnType(c) == 'datetime' || dataView.getColumnType(c) == 'date' ) {
for (var r = 0; r < dataView.getNumberOfRows(); r++) {
newDataTable.setValue(r, c, dataView.getValue(r, c));
}
}
}
return newDataTable;
}
Hope this helps...
J

How to clear chart before adding new data?

I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)

Google multiple GeoMaps, API

How can I use multiple GeoMaps ?
If I have only one map everything is ok. If I try to add another, without loading again the geomap visualization the map doesn't load, and if I try to load them, I get an error: Uncaught TypeError: Object #<Object> has no method 'Load' The function names are the same for the both map, if I change the functions' names for the second map then I have to change the callback
google.setOnLoadCallback(drawMap);
But, if I do so I get the error posted above....
More code:
//first map
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
//second map
<script type="text/javascript">
function drawMap() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
I modified your code as follows and it seems to work now, although you have to be patient for the second map to load. I'm listening for the drawingDone event on the first map before firing off the second map. My theory is that this staggering prevents the two maps from stepping on each other's data structures inside of the Visualization API. But even if I'm wrong about the cause, this at least works.
My changes could use some tidying. Sorry about that. I'm in a bit of a rush, but wanted to get the working code to you before I ran off to do other things.
<script type="text/javascript">
google.load("visualization", "1", {"packages": ["geomap"],"callback": "drawMaps"});
function drawMaps() {
drawMap1();
}
function drawMap1() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("number", "Numar anunturi");
data.setValue(1, 0, 'Ilfov');
data.setValue(1, 1, 6);
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_chart_div");
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
google.visualization.events.addListener(geomap, 'drawingDone', drawMap2);
}
function drawMap2() {
var data = new google.visualization.DataTable();
data.addRows(16);
data.addColumn("string", "City");
data.addColumn("string", "pret/mp:");
data.setValue(0, 0, 'Ilfov');
data.setValue(0, 1, '50.44');
var options = {width: 800,height:400};
options["region"] = "RO";
options["colors"] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options["dataMode"] = "markers";
var container = document.getElementById("map_pret_div");
var geomap2 = new google.visualization.GeoMap(container);
geomap2.draw(data, options);
}
</script>

Categories

Resources