how to add links to google pie chart slices - javascript

This is the code I've been working, I need to redirect to another page by clicking the slices.
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Cleaning Completed', $co1],
['Denied At Client Place', $co2],
['Denied', $co3],
['Postponed', $co4],
['Careless Driver', $co5],
['Cleaning Started', $co6],
['Emptyspace', $co22],
['Assigned to Vehicle', $co23],
['Select', $co24],
['Call Not Picked', $co25],
['Asked to Call Back', $co26],
]);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

I believe Google visualization allows you to set a click handler. So in your drawChart function, add this. (AFTER chart.draw)
google.visualization.events.addListener(chart, 'select', function() {
var selection = chart.getSelection();
console.log(selection);
});
See what "selection" has in it and see if that has enough information to set where the browser should redirect to.
More info: https://developers.google.com/chart/interactive/docs/reference#addlistener

Related

How can a google-chart be created within a new element I've just appended using jQuery?

For context, I'm trying to build a page that displays a google chart for all active sports games that day. A data feed will inform how many there are (in my below example, 3 games going on.) From there, I would like to loop through the set of games, create a div for each one using jQuery, and then place a google chart into each div. Here's what I wrote:
This would come from a data feed:
var activeGames = 3;
Cycle through active games, build a chart for each one
for (i = 0; i < activeGames; i++){
$('.chartContainer').append("<div id='game'></div>");
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Team A');
data.addColumn('number', 'Team B');
data.addRows([1,1]);
//chart data redacted, would come from data feed
var options = {
//chart options redacted, irrelevant
};
var chart = new google.visualization.LineChart(document.getElementById('game'));
chart.draw(data, options);
}
Relevant basics:
linked to jQuery in HTML appropriately
My HTML file is basically just a div for the chartContainer class
The chart displays fine if I create div id='g1' in an html file, but for some reason no charts display when the div is created by jquery, even though the divs DO get created.
Any help is appreciated.
UPDATE: Here's what worked:
Load google charts package
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
Call Function, the for loop goes within:
function drawChart() {
var activeGames = 3;
for (i = 0; i < activeGames; i++){
$('.container').append("<div id='g" + i + "'></div>");
var data = new google.visualization.DataTable();
data.addColumn('number', 'Team A');
data.addColumn('number', 'Time');
data.addRows([1,1]]); //redacted the rest
var options = {};//redacted
var chart = new google.visualization.LineChart(document.getElementById('g'+ i));
chart.draw(data, options);
};
};
load google first, wait for the callback, then draw the charts...
google.charts.load only needs to be called once per page load
no need to load for each chart
since you're creating a new <div> for each chart,
create the div and pass it to the chart's constructor
no need to assign an id, which would need to be unique anyway
see following working snippet...
google.charts.load('current', {
callback: drawCharts,
packages: ['corechart']
});
function drawCharts() {
var activeGames = 3;
for (i = 0; i < activeGames; i++){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Team A');
data.addColumn('number', 'Team B');
data.addRow([1,1]);
var options = {
};
var container = document.createElement('div');
$('.chartContainer').append(container);
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
}
<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 class="chartContainer"></div>
Part of the issue is that the id should be unique to the page. So when creating the div, you should make it unique:
$('.chartContainer').append("<div id='game" + i + "'></div>");
Then, when selecting the div, select the correct div:
var chart = new google.visualization.LineChart(document.getElementById('game' + i));

Google charts tooltip with pie chart isn't shown

Im using google chart to drow pie chart. I need to change slice offset value slice onhover event. I wrote some code but the problem is chart does not display tooltip.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
var options = {
is3D: true,
tooltip: { textStyle: { color: '#000000' }, showColorCode: true }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandlerOver(e) {
//alert('selectHandlerOver');
var row = e.row;
var s = $.parseJSON('{ ' +
'"is3D": "true",' +
'"slices": { "' + row + '": { "offset": "0.2" } },' +
'"animation": { "duration": "100", "easing": "out"}' +
'}')
chart.draw(data, s);
}
function selectHandlerOut(e) {
//alert('selectHandlerOut');
var row = e.row;
var s = $.parseJSON('{"is3D": "true", "slices": { "' + row + '": { "offset": "0.0" } } }')
chart.draw(data, s);
}
google.visualization.events.addListener(chart, 'onmouseover', selectHandlerOver);
google.visualization.events.addListener(chart, 'onmouseout', selectHandlerOut);
chart.draw(data, options);
}
I think this is because O override onmouseover event with custom behaviour. Any suggestions?
This is not because you have overridden the mouse over event. This is because you are calling chart.draw() inside it. Draw method cancels out any tooltips which rendered for the previous.
If you want fine-grained control, You are better off using something like jQueryUI to show your tooltips.

Javascript chart click to open new

I am using a set of data, the amount of CO2 output of the all the US states. So far I split all the states into their corresponding regions. What I am trying to do is; when someone clicks on a region, it would make a new pie chart of the corresponding states. So if click on the section of Northeast region, it would open up a new chart of PA, NY, NH, etc. I am not sure as to how to set up the code for an on click to open new chart. My ultimate goal is to just have it fade out and fade in the new chart. I am rather new to this so I am not too sure. Here is the code that I already have:
<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 data = google.visualization.arrayToDataTable([
['Region', 'CO2 Output'],
['Northeast', 31887048.7],
['Midwest', 64278877.8],
['South', 76192034.1],
['West', 78808504.3],
]);
var options = {
title: 'Average Maximum Co2 Output of the US Regions'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
You can use interactivity as described here https://developers.google.com/chart/interactive/docs/basic_interactivity
See:
// The select handler. Call the chart's getSelection() method
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, selectedItem.column);
alert('The user selected ' + value);
}
}
// Listen for the 'select' event, and call my function selectHandler() when
// the user selects something on the chart.
google.visualization.events.addListener(chart, 'select', selectHandler);
For fading out, you can just use jQuery $('#myChartDiv').fadeOut(); and then just fade in the next chart. You will have to pass a parameter to the second chart so that it knows which one to show.

Google charts not showing axis labels

This is not for the image charts. I have the following code that generates the right chart but the labels don't show. The chart div is in an other div that is used as a tab on my page. When I run the function when the tab containing the chart is not selected, the chart appears with no labels. When I run the function with the tab selected, the labels appear.
drawChart()
}
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Weeks');
data.addColumn('number', 'Indice');
data.addRows(arrIndice1);
var options = {
width:"900",
height:"500",
legend: "none",
title: 'Indice 1',
chartArea:{left:20,top:50,width:"85%",height:"75%"}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
chartArea options seem to cover the axis labels when they increase the chart size. Try removing the chartArea:{left:20,top:50,width:"85%",height:"75%"} part.

Updating Google Visualization API with <div> button

Fellow Coders,
I'm trying to update a Google Visualization API that has already been populated with data. Here's the background:
The user get's to choose several options from drop down menu's. After which, the user may select to update the Google API from a button.
Do I need a QueryWrapper function, initiated through the button onlick, to update the Google API?
HTML code:
<div class="css_button_example" value="UpdateGraph" onclick="showUser()"><span>Update Graph</span></div>
In the above button code, showUser() is a JavaScript function that pulls an MySQL query through PHP - the result is json_encoded back into the Google API JavaScript code. Do I need another JavaScript function to update the Google API?
Here's the Google API code:
google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Cluster');
data.addColumn('number', 'Loans');
data.addColumn('number', 'Lines');
/* create for loops to add as many columns as necessary */
var len = (encoded_cluster_name.length)-27; // encoded_line_volume.length;
data.addRows(len);
for(i=0; i<len; i++) {
var lines = (encoded_line_volume[i])/100000;
var loans = (encoded_loan_volume[i])/100000;
data.setValue(i, 0, ' '+encoded_cluster_name[i]+' ');
data.setValue(i, 1, loans);
data.setValue(i, 2, lines);
}
/*********************************end of loops***************************************/
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height: 300, is3D: true, title: 'Prospect Population', legend: 'right'});
}
Any suggestions on how I can augment the Google API code to update the graph? Maybe a QueryWrapper?

Categories

Resources