How can I get Selection in dashboard with ChartWrapper - google-apps-script

I´m trying to get an event in a google dashboard ChartWrapper.
I need that when I select a row i can throw an event and get the selected value.
Can anyone help me or say me how can I get it?
Here´s my code:
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['controls']});
</script>
<script type="text/javascript">
var data;
var table;
var dash_container;
var myDashboard;
var stringFilter;
var myTable;
function draw() {
// To see the data that this visualization uses, browse to
// http://spreadsheets.google.com/ccc?key=pCQbetd-CptGXxxQIG7VFIQ
data = new google.visualization.Query(
'http://spreadsheets.google.com/tq?key=0Ai3BbtO5JfaodGluSWw0UVFvZ3BDak1nYzVac0RPWGc&pub=1');
// Send the query with a callback function.
data.send(handleQueryResponse);
}
//fin de draw
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
table = response.getDataTable();
// Create a dashboard.
dash_container = document.getElementById('dashboard'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control for the 'Name' column
stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'nombre'}
});
// Table visualization
myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0]} ,
'dataTable': table
});
// Register a listener to be notified once the dashboard is ready.
google.visualization.events.addListener(myDashboard, 'ready', dashboardReady);
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
}
**Here´s where I have the problems, because I can get the selection row
function dashboardReady() {
google.visualization.events.addListener(myTable, 'select', function(event) {
var selection = myTable.getChart().getSelection();
// iterate over all selected rows
for (var i = 0; i < selection.length; i++) {
// do something with selection[i].row
var item = selection[i];
}
alert('Fila seleccionada es: '+item.row +' y la Columna: '+item.column);
});
}
google.setOnLoadCallback(draw);

To do that, you need to do two things after the chart is drawn:
Add a 'ready' event listener to your chart wrapper;
Add a 'select' event listener to the table when the chart wrapper is ready.
So, add the following two lines after myDashboard.draw(table); in your code
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(){
var selection = myTable.getChart().getSelection();
alert(data.getValue(selection[0].row,0));
}
There will be about 3 seconds delay for the ready function to be triggered, due to a bug I think, see here for more details about the bug report of this issue: https://code.google.com/p/google-visualization-api-issues/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Modified%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=1470

With Wrapper you have to add one more function to get selected item i.e. getChart()
Like:
var selectedItem = wrapper.getChart().getSelection()
Remember, Without Wrapper you was getting it by:
var selectedItem = chart.getSelection()

The code working ...
google.setOnLoadCallback(draw);
function draw() {
var data = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
];
var table = google.visualization.arrayToDataTable(data);
// Create a dashboard.
var dash_container = document.getElementById('dashboard');
var myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control.
var stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'Year'}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0, 1]} ,
'dataTable': table,
});
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(e){
var selection = myTable.getChart().getSelection();
var t=table.getValue(selection[0].row, 0);
document.getElementById('label1').innerHTML = t;
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.1', {packages: ['controls']});</script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="filter"></div>
<br>
<div id="table"></div>
<br>
<div id="label1"></div>
</body>
</html>

Related

Export Google visualization as picture

I'm trying to convert a wordtree Google visualization to an image. The current code below runs the wordtree so I can see the visual, but I can't figure out the last section to convert to an image or export as an image. (var my_div = section to end)
I have tried changing code from link below, but can't get it to save as an image.
https://developers.google.com/chart/interactive/docs/printing
I'm also doing this inside of jsfiddle.net to try and make this work.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current'); // Don't need to specify chart libraries!
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
google.visualization.drawChart({
"containerId": "mywordtree",
"dataSourceUrl": "https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing",
"query":"SELECT A",
"chartType": "WordTree",
"options": {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
}
var my_div = document.getElementById('chart_div');
var my_chart = new google.visualization.ChartType(mywordtree);
google.visualization.events.addListener(my_chart, 'ready', function () {
mywordtree.innerHTML = '<img src="' + my_chart.getImageURI() + '">';
});
my_chart.draw(data);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="mywordtree" style="width: 1000px; height: 1000px;"></div>
</body>
</html>
first, in order to generate an image of the chart,
you need to wait for the chart's 'ready' event.
in order to wait for the 'ready' event,
you need access to the chart object.
you will not be able to use the google.visualization.drawChart method,
because it does not return a handle to the chart.
next, the WordTree chart, does not have a method for getImageURI,
so you will need to create the image manually, from a blob.
see following working snippet...
google.charts.load('current').then(function () {
// get chart container
var container = document.getElementById('mywordtree');
// create chart
var chart = new google.visualization.ChartWrapper({
chartType: 'WordTree',
containerId: container.id,
dataSourceUrl: 'https://docs.google.com/spreadsheets/d/1vi-YzV7s7eZ25938Q57DbZvT0iqggiCqRvDgxeZtP6c/edit?usp=sharing',
options: {
wordtree: {
format: 'implicit',
//alt type is 'suffix', 'prefix'
type: 'suffix',
word: 'prescription'
}
}
});
// listen for ready event
google.visualization.events.addListener(chart, 'ready', function () {
var domUrl; // object url
var image; // chart image
var imageUrl; // chart image url
var svg; // svg element
// add svg namespace to chart
svg = container.getElementsByTagName('svg')[0];
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// create image url from svg
domUrl = window.URL || window.webkitURL || window;
imageUrl = domUrl.createObjectURL(new Blob([svg.outerHTML], {type: 'image/svg+xml'}));
// create chart image
image = new Image();
image.onload = function() {
// replace chart with image
container.innerHTML = image.outerHTML;
}
image.src = imageUrl;
});
// draw chart
chart.draw();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="mywordtree"></div>

Google Chart Add Color Specific

How are you?
How do I force the color? I do not want them to be random. I read the documentation, but something is wrong. I can not tell. They help me? Thank you very much!
For Example: I want the Womens records in Black and the mens in Green.
Regarts!
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['status', 'number',{ role: 'style' },{ role: 'annotation' } ],
["Men", 5, '#b87333','M'],
["Girl", 7, '#0000FF','G'],
]);
var options = {
title: 'Sex',
is3D:true,
pieHole: 0.4,
//colors: ['#5cb85c','#f0ad4e']
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>
the only role supported by PieChart is 'tooltip'
both 'style' and 'annotation' are not supported
you can either use the colors configuration option,
colors: ['#5cb85c','#000000']
or the slices option...
slices: [{color: '#5cb85c'}, {color: '#000000'}]
in both options above, the first color in the array will be applied to the first row in the data table,
the second color, the second row, etc...
if you're not sure in which order the data will be,
you can use an object to map the values to a specific color
here, we build the array of colors, by matching the values in the data table,
to the key in the color map object...
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['status', 'number'],
['Men', 5],
['Girl', 7]
]);
var colors = [];
var colorMap = {
'Men': '#5cb85c',
'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
colors.push(colorMap[data.getValue(i, 0)]);
}
var options = {
title: 'Sex',
is3D: true,
colors: colors
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>

geochart regions clickable urls

We want to embed a really basic interactive map on our website, where clicking a region will take you to a specific page on our site. We would like to use the regions in google geochart
This is the map we are working with
https://jsfiddle.net/tyvnfxf4/
google.charts.load('current', {'packages':['geochart']});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['England', 400],
['Wales', 300],
['Scotland', 400],
['Ireland', 600],
]);
var options = {
region: 'GB',
resolution: 'provinces',
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
And we would want:
Wales to link to www.example.com/wales
Ireland to link to www.example.com/ireland
etc
Can any help?
Many thanks
there are a number of ways to handle, but the key is using the 'select' event
keep in mind, the 'select' event is fired both when something is selected and de-selected,
so make sure length > 0
recommend using a column in the DataTable to store the URLs
use a DataView to hide the column from the chart
then get the URL based on the chart selection
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity', 'Domain'],
['England', 400, 'www.example.com/England'],
['Wales', 300, 'www.example.com/Wales'],
['Scotland', 400, 'www.example.com/Scotland'],
['Ireland', 600, 'www.example.com/Ireland'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
region: 'GB',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
console.log(data.getValue(selection[0].row, 2));
//window.open('http://' + data.getValue(selection[0].row, 2), '_blank');
}
});
chart.draw(view, options);
},
packages:['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="regions_div" style="width: 600px; height: 500px;"></div>

Google Dashboard with external JSON input

I have external file with JSON data, and it works properly when I try to generate different charts. Now, I want the data is presented in an interactive way in a dashboard, and I try the Control feature in Google Visualization. Now the chart doesn't show up. What could be the mistake? I test it in a very simple dashboard as follow:
// Load the Visualization API and the controls package.
google.load('visualization', '1.0', {'packages':['controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawDashboard);
function drawDashboard() {
var json3 = (function () {
var json3 = [];
$.ajax({
'async': false,
'global': false,
'url': "Geo.json",
'dataType': "json",
'success': function (data3) {
json3 = data3.rows;
}
});
console.log("Number of message rows: " + json3.length);
return json3;
})();
var readings3 = [];
if (json3.length > 0)
var readings3 = json3;
else
readings3=[
{"Time":"10:00:00 CEST 2013","Lat":58.02794563,"Long":5.45527353,"Speed":12, ...},
{"Time":"13:40:52 CEST 2013","Lat":58.16435456,"Long":5.98108809, "Speed":12, ...}
]
var data3 = new google.visualization.DataTable();
data3.addColumn('string', 'Time');
data3.addColumn('number', 'Lat');
data3.addColumn('number', 'Long');
data3.addColumn('number', 'Speed');
...
...
...
for (var i = 0; i < 1000; i++) {
data3.addRow([
readings3[i].Time,
readings3[i].Lat,
readings3[i].Long,
readings3[i].Speed,
...
...
...
]);
}
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
// Create a range slider, passing some options
var sensordataRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Time'
}
});
var lineChart1 = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'visualization1',
'dataTable': 'data3',
'options': {
'width': 300,
'height': 300,
'legend': 'right'
},
'view': {'columns': [0, 5]}
});
dashboard.bind(sensordataRangeSlider, lineChart1);
dashboard.draw(data3);
}
Thanks in advance.

jQuery Mobile don't' execute function after pageshow

I have in my Phonegap app this JQM; I create a Google map and I load markers from json file.
When i launch page2, i see the first console.log (coordinates) and the last console.log (2222222) - The intermediate console.log that contains numberOfElements is displays only the first time. If I see the map and i return back the whole script isn't loaded.
Why?
$(document).on('pageshow', '#page2', function () {
var latnow = Number(localStorage.getItem("lat"));
var lngnow = Number(localStorage.getItem("lng"));
var coordinate = new google.maps.LatLng(latnow, lngnow);
console.log(latnow + ' ' + lngnow);
$('#map_canvas').gmap({
'center': coordinate,
'disableDefaultUI': true,
'zoom': 5,
'scrollwheel': false,
'panControl': false
});
$('#map_canvas').gmap().bind('init', function () {
var images = "img/icon.png";
var images2 = "img/icon2.png";
$.getJSON('http://www.site.com/app/json.php?lat=' + latnow + '&lat=' + lngnow + '', function (data) {
var myObject = data;
var numberOfElements = data.markers.length;
console.log(numberOfElements); // <- !!!!!!
if (numberOfElements == 0) {
alert("no result");
$.mobile.changePage("#home");
}
var myObject = JSON.stringify(myObject);
localStorage.setItem("json_near", myObject);
$('#map_canvas').gmap('addMarker', {
'position': coordinate,
'icon': images2,
'bounds': true
});
//marker da json
$.each(data.markers, function (i, marker) {
$('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'draggable': false,
'bounds': true,
'icon': images
}).click(function () {
$('#map_canvas').gmap('openInfoWindow', {
'content': marker.content,
'maxWidt': 200,
'maxHeight': 400,
'autoScroll': true
}, this);
});
});
});
});
map_element = document.getElementById("map_canvas");
var mapwidth = $(window).width();
var mapheight = $(window).height();
$("#map_canvas").height(mapheight);
$("#map_canvas").width(mapwidth);
google.maps.event.trigger(map_element, 'resize');
console.log("2222222");
});
I assume you are using this plugin - http://code.google.com/p/jquery-ui-map/ , right?
I think it is not a problem of jquery mobile. The pageshow event is called as you can see from those console.log messages.
Try to stick console.log("xxx") into the gmap init handler. I think this is the one which is NOT called at the second time.
Something like
$('#map_canvas').gmap().bind('init', function () {
console.log("xxxxxx");
var images = "img/icon.png";
var images2 = "img/icon2.png";
...
...
});
do you see xxxxxxx in the console every time you get in the page?
If not, try to find the way how to check whether the map was already initialized (second, third, fourth time, etc.) and then, call getJSON directly.