I am making an application in visual studio with javascript and google charts.
I want to record the graphic, the options I found do not work in IE.
Take an example and modify it, I can move the image to another container <img id = "chartImg" />, on the same page and in this way to save png format.
I also think a popup window to charge image recording.
I can not create the image directly in the popup window, without passing the container <img id = "chartImg" /> and then to the window.
I do not want the container.
As I can create pop-up, directly from SVG is created by plotting with Google Chart API, pressing on a button or click me.
The code place it in jsFiddle.
http://jsfiddle.net/rdmghzhm/3/
It is as follows:
HTML
<div id="visualization"></div>
Right-click this image to save it:<br />
click
<img id="chartImg" />
JAVASCRIPT
function drawVisualizationDaily() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Daily', 'Sales'],
['Mon', 4],
['Tue', 6],
['Wed', 6],
['Thu', 5],
['Fri', 3],
['Sat', 7],
['Sun', 7]
]);
// Create and draw the visualization.
var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'ready', function () {
var imgUri = chart.getImageURI();
// do something with the image URI, like:
document.getElementById('chartImg').src = imgUri;
});
chart.draw(data, {
title:"Daily Sales",
width:500,
height:400,
hAxis: {title: "Daily"}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawVisualizationDaily});
function openWin() {
var divText = document.getElementById("chartImg").outerHTML;
var myWindow = window.open('', '', 'width=500,height=500');
var doc = myWindow.document;
doc.write('<img' + ' id="graficar" ' +' />');
doc.write(divText);
doc.write("<p>This is 'myWindow'</p>");
doc.close();
}
You can hide within a DIV, the image that you create on the main page, the code html would look like this.
<div id="visualization"></div>
Right-click this image to save it:<br />
click
<div style="display:none;">
<img id="chartImg" />
</div>
In jsFiddle serious:
http://jsfiddle.net/3Lx91o0e/
greetings
If there is a small mistake with Chrome, to create the pop-up window, it is still recording the image with right mouse button.
windows.open must call with complete parameter, this code works correctly in Chrome and elsewhere too, I could taste only in IE 11
var myWindow = window.open("about:blank", "Save graph", "location=0,resizable,status=0,menubar=0,titlebar=0,left=5,top=5");
Related
I created an HTML element on my Wix page using Google Charts. My webpage visitors need to fill a questionnaire and the idea would be to give them the results via a pie chart. Here is part of the code of my HTML element:
<script type="text/javascript">
var ctx = document.getElementById('myChart').getContext('2d');
var myPieChart = new Chart(ctx,{
type: 'pie',
data: {
labels:["Rodeo", "Calypso", "Balthazar", "Luna", "Kiara", "Mistral", "Saya"],
datasets: [{
data: [10, 20, 30, 20, 25, 40, 15],
backgroundColor: ["#f97a03", "#52aff0", "#35a11d", "#f052e4", "#853fc2", "#f0f712", "#092978"],
}]
},
options: {}
});
</script>
The code above works great and I can see the chart on the webpage. Now instead of having predetermined data (like 10, 20, 30, 20, 25, 40, 15 above), I would like to use variables whose values are stored in LocalStorage JavaScript (names of variables are the same as per the lables above but with "loc" as a prefix).
I tried:
data: [local.getItem("locrodeo"), local.getItem("loccalypso"),
local.getItem("locsaya"), local.getItem("locbalthazar"),
local.getItem("locluna"), local.getItem("lockiara"),
local.getItem("locmistral")],
But I think APIs don't work with JS under wix HTML component. So I guess I need to send a message from my Page Code to the HTML element with the information in it. Does anyone know how to do that?
From the Wix Help Center, I found that I need to send a message like this:
$w("#myHtmlElement").postMessage("Message for HTML Comp");
And then I need to write code in my HTML element to receive the info:
<script type="text/javascript">
window.onmessage = (event) => {
if (event.data) {
let receivedData = event.data;
}
};
//...
</script>
For clarity, my objective is to have the pie chart showing the values of the variables locrodeo, loccalypso, locsaya, locluna, locbalthazar, locmistral and lockiara (stored in local storage JS).
This example is just about exactly what you want to do: https://www.wix.com/code/home/example/Chart.
I want to show a gauge inside my leaflet popups, with justGage library.
It works fine when I open a popup, or when I close a popup and open another, but if having a popup open, I click on another marker, first popup closes as it should do, and second popup opens, but the gauges are not showing.
This is how I generate the popups:
var myLayer = new L.GeoJSON.AJAX("data/data.geojson", {
onEachFeature: function(feature, layer) {
layer.bindPopup(function (layer) {
$('#myDiv').text();
});
}
});
myDiv is the content of the popup:
<script id="myDiv" type="text/template">
<div>
<div id='gauge1' style='width:60px; height:80px'></div>
</div>
<div>
<div id='gauge2' style='width:60px; height:80px'></div>
</div>
</script>
And I initialize the gauges when the popup opens (this is the only way I got them to work):
myMarkers.on('popupopen', function(e) {
cargaVelocimetro("gauge1", 22);
cargaVelocimetro("gauge2", 33);
}
);
function cargaVelocimetro(id, valor){
if (!gauge) {
var gauge = new JustGage({
id: id,
value: valor,
min: 0,
max: 100,
gaugeWidthScale: 0.8
});
}
}
It's like the fact of not closing properly the first popup affects leaflet in some way?
As Baptiste said in the comment, the IDs are getting mixed up when opening a second popup if the first is still open.
I am creating a map using Google Geochart and need a listener so that when the user clicks on a region it loads a given URL.
My code is:
google.load('visualization', '1.1', {packages: ['geochart'], callback: drawVisualization});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country', 'Value', {role: 'tooltip', p:{html:true}}],
['US', 20, 'Test'],
['Canada', 20, 'http://www.ipfa.org/council/branches/106/ipfa-canada/'],
['GB', 20, 'http://www.ipfa.org/council/branches/52/ipfa-uk/'],
]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
var row = selection[0].row;
var url = data.getValue(row, 3);
window.open(url);
});
chart.draw(data, {
width: 800,
height: 600,
tooltip: {
isHtml: true
}
}
);
}
The URL listener works on another map I use, what am I doing wrong to not work on this one?
There are two issues. First, you are using the wrong index to reference your URLs; they are in column 2, not column 3 (which doesn't exist):
var url = data.getValue(row, 3);
Second, one of your URL's (for the US) is an anchor tag, which won't work if passed to the window.open call. If you want anchor tags in the tooltips, set the value of the cell to the URL and formatted value of the URL column to the anchor tag:
['US', 20, {v: 'http://www.ipfa.org/council/branches/39/ipfa-americas/', f: 'Test'}]
I would also suggest testing for the length of the selection array, because it is possible for the selection array to be empty if the user clicks a region twice in a row (the second click deselects the region), which would cause this line to throw an error:
var row = selection[0].row;
I suggest using this instead:
var selection = chart.getSelection();
if (selection.length) {
var url = data.getValue(selection[0].row, 2);
window.open(url);
}
I am making a google chart whith show and hide functionality.Means chart will be hidden on the page load and when user clicks a button chart will be made visible.
My code
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="display:none; width:800px;height:500px;"></div>
My problem is that when user clicks on the button and chart is visible its not taking the full width and height(800x500).rather its taking an unknown dimension(400x200).
Note: when the chart is made visible in the page load itself, It works correctly.
Code is same change in HTML like this
<div id="chart_div" style=" width:800px;height:500px;"></div>
You can do as marios suggested and set dimensions inside that chart's options, but that won't fix all of the problems that come along with drawing a chart inside a hidden div. The Visualization APIs dimensional measurements don't work well inside hidden divs, so elements get positioned in the wrong place and have the wrong size in some browsers. You need to unhide the div immediately prior to drawing the chart, and you can hide it again when the chart is done drawing. Here's example code that does this:
var container = document.getElementById('chart_div');
container.style.display = 'block';
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
container.style.display = 'none';
});
chart.draw(data, options);
Use chartArea:{} to set width & height
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results',
chartArea: {
width: 800,
height: 500
}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I confirm that this is a bug. It work if the div is hidden "visibility:hidden;"
It does not work if the CSS shows "display:none"
There is an option to ask for specific width and height the google chart api https://developers.google.com/chart/interactive/docs/customizing_charts?hl=es.
Directly give width in chart option.
For eg:
options='{
"width": "800"
}'
How do I redraw/rescale a google linechart on window resize?
To redraw only when the window resize is completed and avoid multiple triggers, I think is better create an event:
//create trigger to resizeEnd event
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
//redraw graph when window resize is completed
$(window).on('resizeEnd', function() {
drawChart(data);
});
The original code by Google simply does this at the end:
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
Changing it with a little javascript you can scale it when the window resizes:
function resize () {
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
window.onload = resize;
window.onresize = resize;
Since the window.resize event fires multiple times on each resize event, I believe that the best solution is to use smartresize.js and use smartdraw(). This limits the number of chart redraw’s per window.resize.
By using the provided js you can do it as simply as this:
// Instantiate and draw our user charts, passing in some options (as you probably were doing it)
var chart = new google.visualization.LineChart(document.getElementById('div_chart'));
chart.draw(data, options);
// And then:
$(window).smartresize(function () {
chart.draw(data, options);
});
This is the simplest way I can work out of doing this without causing too much stress to the browser:
var chart1 = "done";
$(window).resize(function() {
if(chart1=="done"){
chart1 = "waiting";
setTimeout(function(){drawChart();chart1 = "done"},1000);
}
});
All it does is wait 1 second before the chart reloads and doesn't let the function call again in this waiting period. as window resize functions are called multiple times any time you change the window size this helps make the function only actually work once each time you change the window size, the rest of the calls get stopped by the if statement.
I hope this helps
There is no option in Google Visualization API to make Google Charts responsive.
But we can make Google Charts responsive as Window Resizes. To make Google Chart responsive there is jQuery library available at GitHub - jquery-smartresize licensed under MIT License, which has the ability to resize graphs on window resize event.
This project on GitHub has two script files :-
jquery.debouncedresize.js: adds a special event that fires once after the window
has been resized.
&
jquery.throttledresize.js: adds a special event that fires at a reduced rate (no
more double events from Chrome and Safari).
Here are two examples of responsive charts...
Responsive Google Pie Chart
Responsive Google Bar Chart
We can change the bottom padding of visualization_wrap to match the desired aspect ratio of chart.
Calculate as Height / Width x 100
For a 16x9 display it would be 9/16 = 0.5625 x 100 = 56.25%
For a square it'd be 100%
We can customize chartarea option of Google Chart to ensure that labels don't get cut off on resizing.
Redraw/rescale a Google linechart on window resize:
$(document).ready(function () {
$(window).resize(function(){
drawChart();
});
});
I personally prefer the following approach, if You can live with using addEventListener, and don't mind lack of support for IE < 9.
var windowResizeTimer;
window.addEventListener('resize', function(e){
clearTimeout(windowResizeTimer);
windowResizeTimer = setTimeout(function(){
chart.draw(data, options);
}, 750);
});
Note the use of the setTimeout() and clearTimeout() functions and the added delay of 750 milliseconds, which makes this slightly less intensive when multiple resize events fire in quick succession (which is often the case for browsers on desktop when resizing using a mouse).
I've been stuck on the same thing for days and I found out that adding an event works best.
window.addEventListener("resize", drawChart);
Just add this line after declaring your function and it will work fine.
Replace drawChart with the name of your function.
Try with these approaches
window.dispatchEvent(new Event('resize'))
Chartkick.charts["<id of chart element like chart-1>"].redraw()
Using Tiago Castro's answer, I have implemented a line chart to show the demonstration.
google.load('visualization', '1', {
packages: ['corechart', 'line']
});
google.setOnLoadCallback(drawBackgroundColor);
function drawBackgroundColor() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Compute Time');
data.addColumn('number', 'Compute Times');
console.log("--");
data.addRows([
[0, 0, 0],
[10, 10, 15],
[20, 20, 65]
]);
console.log(data);
var options = {
height: 350,
legend: {
position: 'bottom'
},
hAxis: {
title: 'Nb Curves'
},
vAxis: {
title: 'Time (ms)'
},
backgroundColor: '#f1f8e9'
};
function resize() {
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
window.onload = resize();
window.onresize = resize;
}
<script src='https://www.google.com/jsapi'></script>
<div id="chart_div">