Fiddle
I created this fiddle but when try getImageURI() from chart (orgchart google charts) one error is generated.
ERROR: "Uncaught TypeError: chart.getImageURI is not a function"
I need to generate an image or a PDF from orgchart created. Is it possible?
google.charts.load('current', {packages:["corechart","orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
data.addRows([
[{v:'Mike', f:'Mike<div style="color:red; font-style:italic">President</div>'},
'', 'The President'],
[{v:'Jim', f:'Jim<div style="color:red; font-style:italic">Vice President</div>'},
'Mike', 'VP'],
['Alice', 'Mike', ''],
['Bob', 'Jim', 'Bob Sponge'],
['Carol', 'Bob', '']
]);
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
$( "#chart_div2" ).append( '<img src="' + chart.getImageURI() + '">' );
});
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
}
similar to Table Charts, Org charts produce HTML <table> elements, rather than SVG
which is why getImageURI isn't listed in the Methods section for either chart
recommend using library to convert the HTML to Canvas (html2canvas.js),
which can then be saved as base64 string,
similar to getImageURI
see this answer, for a little more info on the topic...
Rendering HTML elements to canvas
try this code:
function printImg() {
html2canvas($('#chart_div').get(0)).then( function (canvas) {
var image = convertCanvasToImage(canvas);
var htmlToPrint = image.outerHTML ;
newWin = window.open("");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
});
}
Don't forget to include html2canvas.js
Related
I am using the google Chart library to display a chart that I want to update only every second.
As I have the code, it is refreshed because using an alert the alert is shown, but the php query does not refresh me... how can I refresh the chart with the included php query?
My code javascrip, used in php
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'D1');
data.addColumn('number', 'D2');
data.addColumn('number', 'D3');
data.addColumn('number', 'V');
data.addRows([
<?
$bus="SELECT * FROM table WHERE Id_test='8574' ORDER BY id DESC LIMIT 15";
$sql=#mysqli_query($con, $bus);
$numer=1;
while($d=#mysqli_fetch_assoc($sql)){
echo '['.$numer.', '.$d[1].', '.$d[2].', '.number_format($d[3],2).'],';
$numer++;
}
?>
]);
var options = {
chart: {
title: 'Title chart',
},
width: 400,
height: 300,
legend: {position: 'none'}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
setInterval(drawChart,1000)
Later show in html
<div id="line_top_x"></div>
have the following function JSONChart()
it reads json data from var "allText" and should be able to parse the data and use it as row data for google charts.
Commenting out the adding row part displays the column data correctly with empty graph.
Need a way to parse the given sample data from a file and display it as row data in the google chart.
function JSONChart() {
google.charts.load('current', {'packages':['corechart']});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var data1 = JSON.parse(allText);
var dataTableData = google.visualization.arrayToDataTable(data1);
data.addRows (dataTableData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// Set chart options
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
'width':1400,
'height':600,
curveType: 'function'
};
chart.draw(data, options);
}
window.onload = function() {
google.charts.setOnLoadCallback(JSONChart());
};
Sample JSON passed into variable "allText"
{"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}
a few things...
1) arrayToDataTable expects a simple array, not a json object
it also returns an entire data table, which has already been created --> data
instead, convert each json object to an array,
then use addRows to add the data to the existing data table --> data
something like...
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
2) google.charts.load -- this statement waits for the window / document to load, before calling the callback
no need for --> window.onload = function() {...
google.charts.load actually returns a promise,
so you can do something like...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// draw chart code here...
3) when passing a callback function to setOnLoadCallback,
a reference to the function should be passed --> JSONChart
not the result of a function --> JSONChart() (remove parens)
4) recommend similar setup as following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var chartData = [];
var data1 = {"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}};
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
height: 600,
curveType: 'function'
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I have an array in my PHP code (budgetingMain.php) called "totals". I want to use it for my data to create a Google Pie Chart. However, I am having difficulty in encoding it.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var jsontotals = <?php echo json_encode($totals) ?>;
// 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', 'Category');
data.addColumn('number', 'Amount Spent on it');
data.addRows([
'jsontotals'
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chartcontainer'));
chart.draw(data, options);
}
</script>
In this current setup, I get the following error: "Uncaught SyntaxError: Unexpected token <" for this line.
var jsontotals = <?php echo json_encode($totals) ?>;
I realise it's an issue with the embedding, but I cannot find a way to get it to work. Any help welcome!
EDIT: This is the structure of totals
$totals = array(
array("ClothingAndAccessories",0),
array("FlowersAndDecorations",0),
array("Ceremony",0),
array("Reception",0),
array("Photography",0),
array("Gifts/favours",0),
array("Stationary",0),
array("Entertainment",0),
array("Other",0)
);
I want to use google pie chart inside jquery and want the chart to be generated based on the condition.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
var options = {title: 'Sample Chart'};
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}
Jquery function,
$.each(result, function(index) {
$("#tableContents").append("some html generation");
});
I want the data1 to be prepared during the loop of Jquery and draw at the end of the function. I see that if I takeout the data1 part of code (shown below) outside the function drawchart, I get
in console log,
Cannot read property 'DataTable' of undefined error
The data1 part of code I removed out of drawChart(),
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
data1.addRow(["sample", 12]);
data1.addRow(["sample", 24]);
Please help, thanks in advance.
You can parse the results into the DataTable like this:
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'col1');
data1.addColumn('number', 'col2');
$.each(result, function(index) {
$("#tableContents").append("some html generation");
// assumes results[index] has "col1Value" and "col2Value" properties
data1.addRow([results[index].col1Value, results[index].col2Value]);
});
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data1, options);
}
Morning, I have the data hidden in the page but im not sure how to add it to the addRows function.
This is what I have:
google.load("visualization", "1", {packages:["corechart"]});
$(document).ready(function(){
var rowArray = [];
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = $(this).next().val();
rowArray.push(["'" + name + "'", amount]);
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Device');
data.addColumn('number', 'Amount');
data.addRows( rowArray );
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {
width: 600,
height: 340,
title: 'Handheld Device Usage',
hAxis: {
title: 'Mobile Device Name',
titleTextStyle: {
color: '#404040'
}
}
});
}
});
Can anyone see where im going wrong?
Regards,
Phil
Maybe this will work:
$('input[name=device_name]').each(function(i){
var name = $(this).val();
var amount = ($(this).next().val() * 1);
rowArray.push([name, amount]);
});
the problem is that amount is a string... I've seen that you're using a js framework so you could probably make a console.log(rowArray); to debug.
a good way to correct that would be if you change this:
var amount = $(this).next().val().toInt();
I've tested it http://jsfiddle.net/TfsFT/1/ and its working. Although i had to change a few things cause i was using Mootools.. and i didn't have the html code :P
Good Luck!