Add Region URL to Geochart - javascript

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);
}

Related

I want to select and highlight country on google Geochart when someone click on a html button or div

I need a country to be selected and highlighted on google Gecochart when a button or Div is clicked.
I was able to achieve that completely if someone clicks on the country on Geochart, but partially if someone clicks the button/div as the Geochart is not highlighting the country until the user moves the mouse pointer above the geochart.
I am trying to implement that using the code below
var chart='';
google.charts.load('current', {
'packages':['geochart'],
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {};
var container =document.getElementById('regions_div');
chart = new google.visualization.GeoChart(container);
observer = new MutationObserver(function (nodes) {
Array.prototype.forEach.call(nodes, function (node) {
// check for new nodes
if (node.addedNodes.length > 0) {
Array.prototype.forEach.call(node.addedNodes, function (addedNode) {
// the tooltip element will also be here, we only want the group elements
if (addedNode.tagName === 'g') {
// find children of the group element
Array.prototype.forEach.call(addedNode.childNodes, function (childNode) {
// check for path element, change stroke
if (childNode.tagName === 'path') {
childNode.setAttribute('stroke', '#FF0000');
//childNode.setAttribute('fill', '#BE965C');
}
});
}
});
}
});
});
// activate mutation observer
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(data, options);
}
function myclick() {
//google.visualization.events.trigger(chart, 'select',[{ row: 3, column: null }]);
chart.setSelection([{ row: 3, column: null }]);
console.log( chart.getSelection());
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>
<div onclick="myclick()">
text
</div>
<button type="button" onclick="myclick()">Click Me!</button>
I also tried to call google.visualization.events.trigger(chart, 'select', chart.getSelection()); to trigger the selection and highlight directly but it didn't work.
Any idea how to to highlight the country when clicking on the button/div directly (without the need to move the mouse over the Gecochart)?
Thank you!
The code can also be found in this snippet https://jsfiddle.net/nmaybar/8p2zruso/
I have solved the issue by changing the version from 'current' to '49' by adjusting the following code:
google.charts.load('current', { 'packages':['geochart'],});
To:
google.charts.load('49', {'packages':['geochart'],});
I am not sure why it doesn't work with version 'current' or 'upcoming'. I think it is a bug.

Show live data on Highcharts without default series

I found this code from Highchart website: https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/dynamic-update/
I want to show data on a chart with empty default series and put dateTime as xAxis. I don't want to use jQuery and do not want to add point on load event in chart. I just want to add point when page is loaded completely. I used this
const chart = new Highcharts.chart('container', {
...
...
...
}
document.addEventListener('DOMContentLoaded', function() {
var i = 0;
console.log(chart)
setInterval(function() {
console.log(values[i])
chart.series[0].addPoint(values[i], true, true);
i++;
}, 1000);
})
I used the chart structure like the link above. values[i] is a point which is [dateTime, Number] that I get it from my an API. I found some solutions that uses category for xAxis but I need to use dateTime and show the dateTime there not category.
You can not add a point with shift to a series without data. Add first point without shift or do not use shift: http://jsfiddle.net/BlackLabel/0h9jz3t1/
const chart = new Highcharts.chart('container', {
series: [{}]
});
const values = [[100, 20], [200, 20], [300, 20], [400, 20], [500, 20]];
document.addEventListener('DOMContentLoaded', function() {
var i = 0;
chart.series[0].addPoint(values[i], true, false);
i++;
setInterval(function() {
chart.series[0].addPoint(values[i], true, true);
i++;
}, 1000);
});
Live demo: http://jsfiddle.net/BlackLabel/oqp30tna/
API: https://api.highcharts.com/class-reference/Highcharts.Series#addPoint

Retrieve value column header google visualisation

I want to retrieve the value of the column header when a user clicks on 1 of the bars of the chart. A report should be generated with the parameters I retrieve from the chart. This is what I have so far:
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.arrayToDataTable([
['Month', '2014', '2015'],
['Jan', 0, 200.00],
['Feb', 0, 400.00],
['Mar', 0, 700.00],
['Apr', 0, 100.00],
['May', 400.00, 900.00],
['Jun', 1100.00, 0],
['Jul', 3400.00, 0],
['Aug', 2500.00, 0],
['Sep', 2450.00, 0],
['Oct', 3170.00, 0],
['Nov', 2500.00, 0],
['Dec', 1979.00, 0]
]);
var options = {
title: 'Raised'
};
var chart = new google.charts.Bar(document.getElementById('chart_div_month'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var month = data.getValue(selectedItem.row, 0);
var year = data.getValue(0, selectedItem.column);
window.location = 'report.php?submit=Submit&year=' + year + '&month=' + month;
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
I am able to retrieve the month parameter, but not the year.
Reading about google chart tables at their API page it says that
getSelection() - Standard getSelection implementation.
Selection elements are all row elements.
Can return more than one selected row.
So getSelection() doesn't select any column, and therefore var year = data.getValue(0, selectedItem.column);won't work.
Why it is like this I don't know, as the getSelection() returns both a row and a column, but the column is always null (thought it hasn't always been like this, there are loads of examples where people show how it works, but they are all broken today).
I have seen an approach that uses standard javascript (or was it jQuery?) to detect which column is clicked (clicked, not selected) by listening for mouseclicks on tds and getting the column property that way, but I can't seem to find it.

How to add more href elements for each column in the chart with Javascript

What I am doing here is add a link for each column but it works only with the first link1's column.
Please help me to correct this problem and make my code shorter when there are not only 3 links for each Plant.
['Year', 'link1', 'Dollars', 'link2', 'Conts', 'link3', 'Quantity'],
['Plant 1', 'http://google.com', 1000, 'http://bing.com', 400, 'http://alexa/com', 2000],
['Tan Thanh', 'http://dell.com', 1170, 'http://lenovo.com', 460, 'http://hp.com', 1420],
['Plant 3', 'http://w3schools.com', 660, 'http://microsoft.com', 1120, 'http://adobe.com', 1080],
['Plant 4', 'http://apple.com', 1030, 'http://htc.com', 540, 'http://samsung.com', 2240]
Summary:
In Plant 1:
Problem goes here:
Click on the first column (blue column), a new tab appears with
http://google.com.
Click on the second column (red column), a new tab appears with
http://google.com.
Click on the third column (yellow column), a new tab appears with
http://google.com.
It must be:
Click on the first column (blue column), a new tab appears with
http://google.com.
Click on the second column (red column), a new tab appears with
http://bing.com.
Click on the third column (yellow column), a new tab appears with
http://alexa/com.
Demo
HTML:
<div id="chart_div" style="width: 550px; height: 500px;"></div>
Javascript:
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'link1', 'Dollars', 'link2', 'Conts', 'link3', 'Quantity'],
['Plant 1', 'http://google.com', 1000, 'http://bing.com', 400, 'http://alexa/com', 2000],
['Tan Thanh', 'http://dell.com', 1170, 'http://lenovo.com', 460, 'http://hp.com', 1420],
['Plant 3', 'http://w3schools.com', 660, 'http://microsoft.com', 1120, 'http://adobe.com', 1080],
['Plant 4', 'http://apple.com', 1030, 'http://htc.com', 540, 'http://samsung.com', 2240]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 2, 4, 6]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
function selectHandler1() {
window.open(data.getValue(chart.getSelection()[0]['row'], 1), '_blank');
}
function selectHandler2() {
window.open(data.getValue(chart.getSelection()[0]['row'], 3), '_blank');
}
function selectHandler3() {
window.open(data.getValue(chart.getSelection()[0]['row'], 5), '_blank');
}
// Add our selection handler.
google.visualization.events.addListener(chart, 'select', selectHandler1);
google.visualization.events.addListener(chart, 'select', selectHandler2);
google.visualization.events.addListener(chart, 'select', selectHandler3);
}
Use a single event handler, and fetch the relevant URL based on the column index of the selected element:
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
// test selection array length, since it can be 0 if the user deselects an element
if (selection.length) {
var row = selection[0].row;
// convert the view column index to the table column index,
// then subtract 1 to get the URL index
var urlCol = view.getTableColumnIndex(selection[0].column) - 1;
window.open(data.getValue(row, urlCol), '_blank');
}
});

Enabling/disabling legend and its corresponding row onclick in Google charts

My requirement is,
After a google chart gets loaded, if I click the legend, the legend should be grayed out and its corresponding value in the graph should be removed.
When I click the grayed out legend, the legend should be highlighted as it was before and the removed value should once again be added to the graph.
I am able to do the 50 % of the first part with the below code:
<html>
<head>
<!--Load the AJAX API-->
<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.
var duplicateChartData = new Array();
var unSelectedArray = new Array();
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
duplicateChartData = new Array();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// 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('chart_div'));
duplicateChartData = data;
function selectHandler() {
var selectedItem = chart.getSelection()[0];
var selectedRow = selectedItem.row;
var isUnSelected = unSelectedArray[selectedRow]
if (selectedItem && !isUnSelected) {
data.setValue(selectedRow, 1, 0);
chart.draw(data, options);
unSelectedArray[selectedRow] = true;
}
if(isUnSelected){
data.setValue(selectedRow, 1, duplicateChartData.getValue(selectedRow,1));
unSelectedArray[selectedRow] = false;
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I basically setValue as 0 for the selected value and try to reset when clicked again. But whenever a zero is set the legend and data gets deleted. But what I want is thw legend to just gray out. ow to achieve this. Please help me.
I did this for line chart. It satisfies your both requirements. Hope this will help you.
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (typeof sel[0].row === 'undefined') {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
Here is the working sample jqfaq.com
Awesome piece of code Abinaya (sorry i cld not +1 im still a newbie here at SO), just what i was looking for, thanks, just a minor correction, based on the comment at jqfaq.com. tried it out and it works 100%.
// if row is undefined, we clicked on the legend
//if (typeof sel[0].row === 'undefined') { *** doesn't seem to work
if (sel[0].row === null) { // this works
checkout the amended jsfiddle
I also had been searching for code on how to get the selected legend label and your code also does that using this line of code
//get selected legend label
data.getColumnLabel(col)
thanks again

Categories

Resources