How to add button to hover tooltip in google chart - charts

I Have tried all the links but no one works with my code
I am trying to add a button to google chart hover tooltip
this is my code
result is data that im bringing to chart
my data need to be grouped all works fine but how i can add a button in
bottom of my tooltip
see the image
`<script>
google.charts.load('current', {packages: ['corechart']});
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable(result, true);
var groupData = google.visualization.data.group(
data,
[1, 0, 2], // group on both columns, age group first
[{
column: 1,
aggregation: google.visualization.data.count,
type: 'number'
}]
);
var view = new google.visualization.DataView(groupData);
// init column arrays
// use age group as first column
var viewColumns = [0];
var aggColumns = [];
// build view & agg columns for each gender
groupData.getDistinctValues(1).forEach(function (surveyName, index) {
// add view column for each gender
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === surveyName) {
return dt.getValue(row, 2);
}
return null;
},
label: surveyName,
type: 'number'
});
// add agg column
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index + 1,
label: surveyName,
type: 'number'
});
});
// set view columns
view.setColumns(viewColumns);
// agg view by age group
var aggData = google.visualization.data.group(
view,
[0],
aggColumns
);
var options = {
title: '',
titleTextStyle: {
color: '#98D015',
fontName: 'Baloo Paaji 2',
fontSize: '25',
margin: 10,
},
titlePosition: 'center',
colors: ['#B42987','3E5F27','#A58C21','#7030A0','#C59EE2','#243254','#F8CBAD','#00B0F0','#B4C7E7','#FFC000'],
theme: 'material',
legend: {
maxLines: 2,
position: 'bottom'
},
chartArea: {top: 20 , width: '80%', height: '60%'},
tooltip: {
isHtml: true,
trigger: 'both'
},
};
// Instantiate and draw the chart.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(aggData, options);
}
google.charts.setOnLoadCallback(drawChart);
`
this is what i am trying to achieve
enter image description here

Related

Popup in WFS layer Openlayers

Good Morning.
To work with wfs layer is it better to use leaflet or openlayers?
I have a code with openlayers that returns WFS from the geoserver. But I'm not able to show the attributes in popup. can anybody help me?
Thanks
You can try ol-ext ol/Overlay/PopupFeature to display feature attributes in a popup.
See example: https://viglino.github.io/ol-ext/examples/popup/map.popup.feature.html
Following the example of https://viglino.github.io/ol-ext/examples/popup/map.popup.feature.html, I have this code where my WFS layer contains the id and name attributes, however, it doesn't show anything in the popup
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: function(extent) {
return 'http://localhost:8080/geoserver/teste/wfs?service=WFS&' +
version=1.1.0&request=GetFeature&typename=teste:MYLAYER&' +
'outputFormat=application/json&srsname=EPSG:4326&' +
'bbox=' + extent.join(',') + ',EPSG:4326';
},
strategy: ol.loadingstrategy.bbox
});
var vector = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
var layers = [
new ol.layer.Tile({source: new ol.source.OSM()}),
vector,
];
var map = new ol.Map({
layers: layers,
interactions: ol.interaction.defaults({ altShiftDragRotate:false, pinchRotate:false }),
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([-46.444137, -23.713596]),
zoom: 12
})
});
var select = new ol.interaction.Select({
hitTolerance: 5,
multi: true,
condition: ol.events.condition.singleClick
});
map.addInteraction(select);
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select,
canFix: true,
template: {
title:
function(f) {
return f.get('nome')+' ('+f.get('id')+')';
},
attributes: // [ 'id', 'nome' ]
{
'nome': { title: 'Nome' },
'id': { title: 'Id' },
}
}
});
map.addOverlay (popup);
This is the popup code. I have 3 layers: layer1, layer2 and layer3.
For layer1, ID I want to show as ID. For layer2, I want to show ID as CODE and for other layers I don't want to show ID attribute.
How should I change the template? Thanks
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select_interaction,
canFix: true,
template: {
title:
function(f) {
return f.get('NAME')+' ('+f.get('ID')+')';
},
attributes:
{
'ID': { title: 'ID' },
// with prefix and suffix
'POP': {
title: 'População', // attribute's title
before: '', // something to add before
format: ol.Overlay.PopupFeature.localString(), // format as local string
after: ' hab.' // something to add after
},
}
}
});
#user12538529
You have to create a function and return the template for each case:
// Create templates
var templateID = { ... };
var templateCODE = { ... };
// Popup with a template function
var popup = new ol.Overlay.PopupFeature({
popupClass: 'default anim',
select: select_interaction,
canFix: true,
template: function(feature) {
var prop = feature.getProperties();
// Test if has property ID
if (prop.hasOwnProperty('ID')) return templateID;
// or property CODE
else if (prop.hasOwnProperty('CODE')) return templateCODE;
}
});

Set Automatic Tooltip 0dp Percentage on Google Donut Chart

Using Google Charts Donut Chart it handily produces a tooltip with a calculated percentage along with the text descriptor and base count.
However I'd like to adjust this to 0dp but can't see a way to do this in the documentation without doing HTML tooltips which seem to be overkill for a simple rounding of a decimal point.
You can see the issue here, where it's shown to 1dp as there's more to it, however, here it's rounded to 0dp due to it being an integer:
So, for consistency and ease for viewers, I'd like to just round this all off at 0dp.
The code I'm using is:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['NPS', 'Count'],
['Detractor', 25],
['Neutal', 31],
['Promoter', 48],
]);
var options = {
legend: 'none',
pieSliceText: 'none',
pieHole: 0.7,
slices: {
0: { color: '#232944' },
1: { color: '#a5a5a5' },
2: { color: '#a9d136' }
}
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
there is not an option to format the percentage value shown in the tooltip.
the only option is a custom tooltip.
see following working snippet.
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['NPS', 'Count'],
['Detractor', 25],
['Neutal', 31],
['Promoter', 48],
]);
var groupData = google.visualization.data.group(
data,
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[{
column: 1,
type: 'number',
label: 'Total',
aggregation: google.visualization.data.sum
}]
);
var total = groupData.getValue(0, 1);
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0'
});
var formatPercent = new google.visualization.NumberFormat({
pattern: '#,##0%'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var label = dt.getValue(row, 0);
var value = dt.getValue(row, 1);
var percent = '';
if (total > 0) {
percent = ' (' + formatPercent.formatValue(value / total) + ')';
}
return label + '\n' + formatNumber.formatValue(value) + percent;
},
role: 'tooltip',
type: 'string'
}]);
var options = {
legend: 'none',
pieSliceText: 'none',
pieHole: 0.7,
slices: {
0: { color: '#232944' },
1: { color: '#a5a5a5' },
2: { color: '#a9d136' }
},
tooltip: {
textStyle: {
bold: true
}
}
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="donutchart"></div>

Format number with . as thousand separator and no decimals

I've alreayd checked here:
https://groups.google.com/forum/#!topic/google-visualization-api/4qCeUgE-OmU
https://developers.google.com/chart/interactive/docs/querylanguage#Format
https://developers.google.com/chart/interactive/docs/reference#numberformatter
I want to display the number on the x-axis in a graph drawn with Google Charts with no decimals and a . as the thousand separator.
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Price (€)', format: '#.###'
}
};
So 3200 should be shown as 3.200
I've already tried for the format variable:
#.#
#.###
#
since the format option will not work in this situation,
you can provide your own ticks for vAxis...
use object notation for each tick
{
v: value,
f: formattedValue
}
use google's NumberFormat class...
var formatNumber = new google.visualization.NumberFormat({
fractionDigits: 0,
groupingSymbol: '.'
});
format each tick using the formatValue method
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addRows([
[1, 3000],
[2, 3100],
[3, 3200],
[4, 3300],
[5, 3400],
]);
var formatNumber = new google.visualization.NumberFormat({
fractionDigits: 0,
groupingSymbol: '.'
});
var columnRange = data.getColumnRange(1);
var ticks = [];
for (var i = columnRange.min; i <= columnRange.max; i=i+100) {
ticks.push({
v: i,
f: formatNumber.formatValue(i)
});
}
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
ticks: ticks,
title: 'Price (€)'
}
};
var container = document.getElementById('chart');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

How to skip empty rows from displaying in a google bar chart?

I find that empty rows are being displayed too in a google bar chart.
You could exclude empty rows from google.visualization.DataTable like this:
function excludeEmptyRows(dataTable)
{
var view = new google.visualization.DataView(dataTable);
var rowIndexes = view.getFilteredRows([{column: 1, maxValue: 0}]); //get rows with 0 values
view.hideRows(rowIndexes); //hide empty rows
return view.toDataTable();
}
Example
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population',],
['New York City, NY', 8175000],
['Los Angeles, CA', 3792000],
['Chicago, IL', 2695000],
['Houston, TX', 2099000],
['Philadelphia, PA', 1526000],
['---', 0]
]);
var options = {
title: 'Population of Largest U.S. Cities',
chartArea: {width: '50%'},
hAxis: {
title: 'Total Population',
minValue: 0
},
vAxis: {
title: 'City'
},
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(excludeEmptyRows(data), options);
}
function excludeEmptyRows(dataTable)
{
var view = new google.visualization.DataView(dataTable);
var rowIndexes = view.getFilteredRows([{column: 1, maxValue: 0}]); //get rows with 0 values
view.hideRows(rowIndexes); //hide empty rows
return view.toDataTable();
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>

retreival of x-axis value on a google chart getselection

I use a column chart. When clicking at one of the rows in the diagram my listener trigger an event:
google.visualization.events.addListener(chart, 'select', renderList);
I am only able to retrieve the number 2456 and not 6. Number 6 is the value of my first column. I have two columns in my table. Can someone please help me with this? I've been struggling for quite some time.
This is the instantiation of the chart:
<script type="text/javascript">
$("select").change(function () {
drawChart();
});
function drawChart() {
var inputData = {
rooms: $("#Rooms").val(), area: $("#Areas").val(), apartmentType: $("#ApartmentType").val(),
queue: $("#Queue").val(), year: $("#Years").val()
}
$.ajax({
url: '#Url.Action("AllocatedApartments", "Statistics")',
dataType: 'json',
data: inputData,
type: 'POST',
success: function (data) {
tdata = new google.visualization.DataTable();
tdata.addColumn('number', 'Antal bostäder');
tdata.addColumn('number', 'Kötid');
$.each(data.GroupedList, function (key, value) {
tdata.addRow([value.QueueTime, value.Count])
});
var options = {
title: 'Förmedlade bostäder',
backgroundColor: "F1F1F1",
colors: ['73a948'],
legend: { "position": "none" },
vAxis: { title: 'Antal förmedlade bostäder', titleTextStyle: { color: 'gray' } },
hAxis: { title: 'Kötidsintervall (antal år)', titleTextStyle: { color: 'gray' } }
};
chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
google.visualization.events.addListener(chart, 'select', renderList);
}
});
}
</script>
In the function renderList I want to fetch the label of the row selected:
function renderList() {
var selection = chart.getSelection();
var value = tdata.getValue(selection.row, selection.column );
alert(value)
$.ajax({
url: '#Url.Action("RenderApartmentList", "Statistics")',
dataType: 'json',
type: 'POST',
data: inputData,
success: function (data) {
var html = Mustache.to_html(template, data)
$("#myPartialViewContainer").html(html);
},
error: function (xhr) {
alert("Ett fel uppstod, var god försök igen om en liten stund.")
}
});
}
For this part of code
function renderList() {
var selection = chart.getSelection();
var value = tdata.getValue(selection.row, selection.column );
alert(value)
...
you have to receive error in console log:
Uncaught Error: Invalid row index undefined. Should be in the range [0-53].
getSelection() returns an array. So you have to change that to:
function renderList() {
var selection = chart.getSelection();
var value = tdata.getValue(selection[0].row, selection[0].column );
See google docs about Column chart: getSelection() Array of selection elements
And Extended description of getSelection()