Google Visualization - Select Handler not working - google-visualization

I'm hoping this is a problem that's really easy to fix. Having copied all of the necessary code from the Google Visualization site, everything is working with one exception. I have a data table where, if I select a row, the select handler is called - but I am unable to get table.getSelection() to work
I've seen a suggestion that I might need to include getChart(), but that doesn't fix it (at least not in any of the ways I tried).
In the extract below, I get the first alert message when selecting a row, but not the second, as the code stops running at the table.getSelection() line.
Can anyone suggest what the problem might be?
Many thanks!
<html>
</body>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable_1);
function drawTable_1() {
js_booking = <?php echo json_encode($arr_booking); ?>;
js_name = <?php echo json_encode($arr_name); ?>;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (i = 0; i < 5; i++) {
data.addRows([
[js_booking[i], js_name[i]]
]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
google.visualization.events.addListener(table, 'select', selectHandler);
}
function selectHandler(e) {
alert('A table row was selected');
var selection = table.getSelection();
alert('Selection identified');
}
</script>
</head>
<body>
<div id="table_div_1">Loading...</div>
</body>
<br>
</html>

don't really see a problem with the code, seems to work fine here.
only minor issue...
generally, chart events should be assigned after the chart is created but before the chart is drawn.
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (var i = 0; i < 5; i++) {
data.addRow(['Booking ' + (i + 1), 'Name ' + (i + 1)]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
google.visualization.events.addListener(table, 'select', selectHandler);
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
function selectHandler(e) {
console.log('A table row was selected');
var selection = table.getSelection();
console.log('Selection identified', JSON.stringify(selection));
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div_1"></div>

Related

Chart js with json file from url

I am new here so please forgive my errors in asking. I am working on a personal project with json file from external url. But the graph does not shown up. Chrome compiler says that
Chart.min.js:12 Uncaught TypeError: t.ticks.map is not a function
Chart.min.js:12 Uncaught TypeError: Cannot read property 'initialize' of undefinedeventHandler # Chart.min.js:12(anonymous function) # Chart.min.js:12i.(anonymous function) # Chart.min.js:12
Note: Arrays are getting the values
(Sorry if I ask this wrong way I will try to improve my questions)
<html>
<head>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var name;
var count;
$(document).ready(function () {
var jsonurl = "http://avare.pe.hu/veri2.json";
$.getJSON(jsonurl, function (json) {
name = json[0]['names'];
count = json[0]['count'];
for (var i = 0; i < 5; i++)
console.log(name[i] + count[i]);
});
})
var canvas = document.getElementById('myChart');
var dataSet = {
labels: name,
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: count,
}
]
};
var option = {
animation: {
duration: 5000
}
};
var myBarChart = Chart.Bar(canvas, {
data: dataSet,
options: option
});
</script>
</body>
</html>
Issue comes from the async call to get the data. You start the chart initialization after this call but because it is async name and count will be undefined at the time you create the chart.
Quick fix is to place the chart creation inside the success callback of the getJSON
https://fiddle.jshell.net/leighking2/45x1f09v/

not enough columns to draw -google charts

I have tried to pass some array data to google charts but it says not enough columns to draw chart.here is my code.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1=someStr.replace(/(["'])(\d+)\1/g,"$2")
console.log(data1);
var data = google.visualization.arrayToDataTable([['year'],[data1]]);
console.log(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
</body>
</html>
Please help me to do this.
Thank in advance.
Your data has two columns: Month and a Number. ("JAN","1088626")
But you're only providing a header for one column: year
Plus, you need to pass an actual array to arrayToDataTable. (not a string)
Try something like this...
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1 = JSON.parse('[' + someStr.replace(/(["'])(\d+)\1/g,"$2") + ']');
// data array - add two column headings to data1
data1.splice(0, 0, ['month', 'number']);
// data table
var data = google.visualization.arrayToDataTable(data1);
// chart options
var options = {
title: 'My Daily Activities',
is3D: true
};
// chart
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
You are getting this error since invalid input data is passed into google.visualization.arrayToDataTable function. The provided regex /(["'])(\d+)\1/g fails while parsing the input string, i would suggest to parse input string with JSON.parse function.
google.visualization.PieChart object expects data to be provided in
the following format:
var data = google.visualization.arrayToDataTable([
['Name', 'Value'],
['<name1>', <value1>],
['<name2>', <value2>],
['<name3>', <value3>],
...
['<namen>', <valuen>]
]);
Below is provided the modified example:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var stringData = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data = JSON.parse("[" + stringData + "]");
data = data.map(function (item) {
item[1] = parseInt(item[1]);
return item;
});
data.splice(0, 0, ['year', 'hours']);
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(dataTable, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>

Google Visualization Line Chart using Google Sheet Code Example

I'm looking for sample code for using a Google Sheet as the source data and make a fairly simple line chart using Google Visualization.
I noticed that the new Google Sheets don't include a script in the "Share Chart" function, they offer a IFRAME and the width/height doesn't work. So, I'm looking to do it with Google Visualizations.
Here is my sample chart.
Thank you for the help.
Edited...
Here is my spreadsheet.
Here is my HTML file.
<html>
<head>
<script type="text/javascript">
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key=14MXilv-uhEAUxDzVB7qVCCmQYqkmWvqqaBOXeBsS04k&gid=0');
query.setQuery('SELECT A, B, C, D, E');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('linechart'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChart
});
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id="linechart"></span>
</body>
</html>
It doesn't draw. I've tried various selection in the spreadsheet like avoiding column A, no go. What am I doing wrong?
Here's some example code to get you started:
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key={spreadsheet key}&gid=0');
query.setQuery('SELECT A, B, C');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
You would need to replace the {spreadsheet key} in the URL with your own spreadsheet key (eg: 'http://docs.google.com/spreadsheet/tq?key=1234567890&gid=0') and change the query to select the appropriate columns from your spreadsheet.
In your page's HTML, you need to have a container div that matches the ID used when creating the chart ('chart_div' in this case):
<div id="chart_div"></div>

Can any tell me how add two needles in Gauge graph Using Google charts

I want to display two values in a single gauge graph using two needles. How can I do that.
Can any one please suggest me of doing it.
I have tried with following code But I am not success full.
And I got this following error.
GET http://5.39.186.164/%7B%22cols%22:[%7B%22label%22:%22Q7%22,%22type%22:%22nu…r%22%7D],%22rows%22:[%7B%22c%22:[%7B%22v%22:43%7D,%7B%22v%22:21%7D]%7D]%7D 404 (Not Found)
<!--Load the AJAX API -->
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['gauge']});
</script>
<script type="text/javascript">
var gauge;
var gaugeData;
var gaugeOptions;
function drawGauge() {
//var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
//var obj = eval ("(" + response + ")");
$.getJSON('<?php echo json_encode($response); ?>', function(json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
for (x in json) {
data.addRow([x, json[x]]);
}
//gaugeData = new google.visualization.DataTable(response);
gauge = new google.visualization.Gauge(document.getElementById('gauge'));
gaugeOptions = {
width: 2000,
height: 150,
greenFrom: 0,
greenTo: 50,
redFrom: 75,
redTo: 100,
yellowFrom:50,
yellowTo: 75,
minorTicks: 5
};
gauge.draw(gaugeData, gaugeOptions);
//chart.draw(data, options);
});
}
google.load('visualization', '1', {packages:['gauge'], callback: drawGauge});

getSelection() to get data from row in Google Chart API

I'm trying to trigger the creation of a new BarChart with Google's Chart API when a user clicks on a particular bar. I think I understand the concepts, and wanted to at least get the getSelection() function to work and display what bar the user clicked on. But everytime, when you click on the bar, it just freezes with the display and no java alert. Any thoughts?
Here's the code:
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var visualization = new google.visualization.BarChart(document.getElementById('acctmeta'));
var json_data = new google.visualization.DataTable({{acctmeta_json}});
visualization.draw(json_data, {width: 850, height: 600, title: 'Collection Level Populated Metadata Fields',
chartArea: {width:"50%"},
vAxis: {title: 'Collection Title/ID', titleTextStyle: {color: 'green'}},
hAxis: {logScale:false, title:'Fields Populated', titleTextStyle: {color: 'green'}}
});
// Add our selection handler.
google.visualization.events.addListener(visualization, 'select', selectHandler);
// The selection handler.
// Loop through all items in the selection and concatenate
// a single message from all of them.
function selectHandler() {
alert(data.getValue(chart.getSelection()[0].row, 0));
}
} //end of draw chart function
</script>
Just wondering, should the line
alert(data.getValue(chart.getSelection()[0].row, 0));
be
alert(data.getValue(visualization.getSelection()[0].row, 0));
?
Here is a working example of mine. I had to set data and chart as global variables:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
var data;
var chart;
function drawChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Where');
data.addColumn('number', 'What');
data.addRows([['ABC',87],['ERT',70],['KLJ',38],['UPP',-67],['SSD',27],['UKG',42],['NUS',60],['WEB',96]]);
var options = {'title':'my chart','width':'600','height':'400','is3D':'true'};
chart = new google.visualization.ColumnChart(document.getElementById('test3_chart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler2);
}
function selectHandler2() {
var selection = chart.getSelection();
alert('That\'s column no. '+selection[0].row);
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id=test3_chart>Please wait...</div>
</body>
</html>