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?
Related
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));
Does any of you know of a simple way to add distance on the X-axis of the Google maps elevation chart example (https://developers.google.com/maps/documentation/javascript/examples/elevation-paths)?
I have seen several entries here on SO about this but none has a working answer referring to a JSFiddle or similar.
Thanks in advance for any input!
Regards
/Peter
I created a simplified solution that uses the code provided by Google accompanied with some minor modifications that assign distance to each column based on the total distance divided by the amount of columns. See modified excerpt from the sample code below;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Distance');
data.addColumn('number', 'Height');
for (var i = 0; i < elevations.length; i++) {
data.addRow([Math.round(((totalDistance/amountOfColumns)*i)) + " m",elevations[i].elevation]);
}
// Draw the chart using the data within its DIV.
chart.draw(data, {
height: 150,
legend: 'Height profile',
titleY: 'Height (m)',
titleX: 'Distance (m)',
hAxis: {
title: 'Distance (m)',
},
vAxis: {
title: 'Height (m)'
},
colors: ['#000000']
});
}
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.
Is there any JavaScript out there or examples for horizontally panning a Google Column Chart?
I have several months worth of data and I would like the users to be able to view it left to right. This is the functionality I would like: http://almende.github.io/chap-links-library/js/graph/examples/example05_gaps_in_data.html. My users have pushed back against using an Annotated TimeLine.
You can hook a ColumnChart up to a ChartRangeFilter and get the pan and zoom functionality of the AnnotatedTimeline.
[Edit]
The new version of the Visualization API supports zooming and panning charts via the explorer option. The default allows users to zoom with the scroll wheel and pan by clicking and dragging. Here's an example:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y');
var y = 50;
for (var i = 0; i < 1000; i++) {
y += Math.ceil(Math.random() * 3) * Math.pow(-1, Math.floor(Math.random() * 2));
data.addRow([i, y]);
}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {
height: 400,
width: 600,
explorer: {
axis: 'horizontal',
keepInBounds: true
}
});
}
google.load('visualization',
jsfiddle: http://jsfiddle.net/asgallant/KArng/
Ironically the library I referenced is actually using Google Visualization charts and doing some amazing things with them, including panning.
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