Load popup on hover data from json file for datamaps - javascript

The datamaps "Getting started" page has a section on customizing the text when a user hovers over a specific country. However, they do so by hard-coding that info:
<script>
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(0,0,0)',
defaultFill: 'green'
},
data: {
IRL: {
fillKey: 'LOW',
numberOfThings: 2002
},
USA: {
fillKey: 'MEDIUM',
numberOfThings: 10381
}
},
geographyConfig: {
popupTemplate: function(geo, data) {
return ['<div class="hoverinfo"><strong>',
'Number of things in ' + geo.properties.name,
': ' + data.numberOfThings,
'</strong></div>'].join('');
}
}
});
</script>
I would like to load that info from an external .json file so that I can update it easily. How can I do this? I've tried setting dataURL, but that expects a complete topojson file, which I don't need to update.
Any help greatly appreciated!

dataUrl at the root level can take a json or csv file, like this example here: http://bl.ocks.org/markmarkoh/11331459
var election = new Datamap({
scope: 'usa',
element: document.getElementById('container1'),
geographyConfig: {
popupTemplate: function(geo, data) {
return data && data.info && "<div class='hoverinfo'><strong>" + data.info + "</strong></div>";
},
highlightOnHover: false,
borderColor: '#444',
borderWidth: 0.5
},
dataUrl: 'data.json',
dataType: 'json',
data: {},
fills: {
'Visited': '#306596',
'neato': '#0fa0fa',
'Trouble': '#bada55',
defaultFill: '#dddddd'
}
});
While the resource at data.json looks like:
{
"NY": {"fillKey": "Visited", "anotherProperty": "Born here"},
"TX": {"fillKey": "Visited", "anotherProperty": "Live here"},
"CA": {"fillKey": "Visited", "anotherProperty": "Here while writing this code"}
}

Related

Layer in Leaflet JS doesnt show again when check the control layer

I use the leaflet control layer to show up and remove the layer when I didn't wanna show the layer. when I uncheck my control layer it worked properly. the layer can disappear, but when I check again the control layer, the layer didn't show again. but there is no error in the console .
var pieChartGroup = L.featureGroup().addTo(map);
vals.forEach(val => {
var pictures = L.marker(val.location, {
icon: L.divIcon({
className: 'leaflet-echart-icon',
iconSize: [160, 160],
html: '<div id="marker' + val.id + '" style="width: 160px; height: 160px; position: relative; background-color: transparent;"></div>'
})
}).addTo(pieChartGroup);
// Based on the prepared dom, initialize the echarts instance
var myChart = echarts.init(document.getElementById('marker' + val.id));
// Specify chart configuration items and data
option = {
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
series: [{
name: val.nama,
type: 'pie',
radius: ['10', '25'],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '18',
fontWeight: 'bold'
}
}
},
labelLine: {
normal: {
show: false
}
},
data: [{
value: val.MB,
name: 'Masih Bersekolah'
}, {
value: val.TBL,
name: 'Tidak Bersekolah Lagi'
}, {
value: val.TBPS,
name: 'Tidak/Belum Pernah Bersekolah'
}]
}]
};
// Use the configuration items and data you just specified to display the chart.
myChart.setOption(option);
}
)
var baseLayers = {
"OpenStreetMap": LayerKita,
"OpenCycleMap": L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'),
"Outdoors": L.tileLayer('http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png')
};
var overlays = {
"Bersekolah" : pieChartGroup
};
L.control.layers(baseLayers, overlays).addTo(map);

Highchart JS Set data not updating Export: ShowTable on Dropdown Event but chart updates fine

I have an .aspx file which has drop-down lists and on selected index changed a javascript function is being called to update the series data points on a highchart rather than rendering the entire chart again. I have created the below function but this doesnt seem to be updating the highchart table.It works when updating the chart.
Used this example to create the chart and table that synchronize together:
https://www.highcharts.com/blog/tutorials/synchronize-selection-bi-directionally-between-chart-and-table/
But when I click an item on the dropdown which refreshes the points using setData the table is not updating the values!!!
function salesPurchaseScatter() {
console.log("I am in the function");
var scatterData = [];
var xAxisLabels = [];
var scatterDatas;
$.ajax({
type: "POST",
async: false,
url: "Index.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
scatterDatas = data.d;
}
});
const chart = window.chart;
console.log("CHart: ", chart);
chart.series[0].setData(scatterDatas.map(item => item["bucket5"]));
chart.series[1].setData(scatterDatas.map(item => item["bucket10"]));
chart.series[2].setData(scatterDatas.map(item => item["bucket15"]));
chart.series[3].setData(scatterDatas.map(item => item["bucket20"]));
chart.series[4].setData(scatterDatas.map(item => item["bucket25"]));
chart.series[5].setData(scatterDatas.map(item => item["bucket30"]));
chart.viewData();
}
The above is not updating the data points on the data table!
My original function to create the chart in the first place which works fine is below:
var scatterData = [];
var xAxisLabels = [];
var scatterDatas;
$.ajax({
type: "POST",
async: false,
url: "Index.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
scatterDatas = data.d;
}
});
let chart = Highcharts.chart('container1', {
chart: {
type: 'scatter',
events: {
selection: selectPointsByDrag,
click: unselectByClick
},
// necesssary to be able to select by dragging
zoomType: 'xy'
},
title: {
text: '(' + minDWT + ' <DWT ' + ' < ' + maxDWT + ')',
style: {
fontWeight: 'bold',
fontSize: '20px'
}
},
plotOptions: {
scatter: {
lineWidth: 2,
dashStyle: 'dot'
},
series: {
connectNulls: true,
allowPointSelect: true,
pointPadding: 0,
point: {
events: {
select: function (e) {
selectTableCell(this, true);
},
unselect: function (e) {
selectTableCell(this, false);
}
}
},
marker: {
states: {
select: {
fillColor: 'tomato',
borderColor: 'green'
}
}
}
}
},
series: [{
name: 'bucket5',
data: scatterDatas.map(item => item["bucket5"]),
turboThreshold: 0,
id: 'Results1',
marker: {
symbol: 'circle'
},
},
{
name: 'bucket10',
data: scatterDatas.map(item => item["bucket10"]),
turboThreshold: 0,
id: 'Results2',
marker: {
symbol: 'circle'
},
},
{
name: 'bucket15',
data: scatterDatas.map(item => item["bucket15"]),
turboThreshold: 0,
id: 'Results3',
marker: {
symbol: 'circle'
},
},
{
name: 'bucket20',
data: scatterDatas.map(item => item["bucket20"]),
turboThreshold: 0,
id: 'Results4',
marker: {
symbol: 'circle'
},
},
{
name: 'bucket25',
data: scatterDatas.map(item => item["bucket25"]),
turboThreshold: 0,
id: 'Results5',
marker: {
symbol: 'circle'
},
}, {
name: 'bucket30',
data: scatterDatas.map(item => item["bucket30"]),
turboThreshold: 0,
id: 'Results6',
marker: {
symbol: 'circle',
fillColor: 'red',
radius: 10
},
}],
xAxis: {
categories: scatterDatas.map(item => item["date"])
},
tooltip: {
formatter: function () {
var s = '<span style="color:' + this.point.color + '">\u25CF</span> ' + this.point.series.name + '<br /><b>Date: ' + this.x + '</b><br/><b>Sales Price: ' + this.y + '</b>';
return s;
}
},
exporting: {
showTable: true
},
});
UPDATE:
I have managed to get a step further. The chart is updating with the new data points but the table is not :
exporting: {
showTable: true
},
The fix i put in place:
const chart = window.chart;
console.log("CHart: ", chart);
for (i = 0; i < chart.series.length; i++) //Added this
chart.series[i].setData([]);
chart.series[0].setData(scatterDatas.map(item => item["bucket5"]));
chart.series[1].setData(scatterDatas.map(item => item["bucket10"]));
chart.series[2].setData(scatterDatas.map(item => item["bucket15"]));
chart.series[3].setData(scatterDatas.map(item => item["bucket20"]));
chart.series[4].setData(scatterDatas.map(item => item["bucket25"]));
chart.series[5].setData(scatterDatas.map(item => item["bucket30"]));
chart.viewData();
chart.redraw(); //Added this
Have i missed something out? Struggling to debug and identify what is going wrong
Found a JSFiddle which is similar to my current set up. http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/export-data/showtable/
The above JS Fiddle has a similar chart and table output. When i click on a drop down item I am trying to setData (the data point values) as per above code and this should update the chart and table. In my case it is only updating the chart and not the table. The function I am calling is salesPurchaseScatter on dropdown selected index changed event.
ATTEMPTED THIS:
const table = window.table;
table.series[0].setData(scatterDatas.map(item => item["saleagebucket5"]));
table.series[1].setData(scatterDatas.map(item => item["saleagebucket10"]));
table.series[2].setData(scatterDatas.map(item => item["saleagebucket15"]));
table.series[3].setData(scatterDatas.map(item => item["saleagebucket20"]));
table.series[4].setData(scatterDatas.map(item => item["saleagebucket25"]));
table.series[5].setData(scatterDatas.map(item => item["imo"]));
chart.redraw();
table.redraw();
but series is not possible using a table. How can i update the data using setData for the table? I tried using chart.viewData() but this doesnt seem to work either.
My guess is: const chart= window.chart; is only referring to the chart but dont know how to re-do the entire high chart canvas just the chart on it own!
A JSFiddle I tried to follow - https://jsfiddle.net/hxgp0yvj/
but same issue happening- Table not updating in this but chart does. I moved the code into my own solution to test it out. What am i missing?
Thank you for sharing it, after digging into I found out that it is a regression. I reported it on the Highcharts GitHub issue channel where you can follow this thread. If you don't need any new functionalities please use the previous version of the Highcharts until the bug will be fixed.
https://github.com/highcharts/highcharts/issues/14320

How to migrate a chart from Highcharts Demo to Highcharts Cloud

Perhaps others have seen the amazing Force-Directed Network Graph demo which I would dearly love to adapt to my own ends. However, simply copying the code over doesn't seem to be enough.
I'm no longer using the inline-defined data but rather data coming from a Google Sheets file. And I've morphed the code so that it contains more columns in the data. Here's a jsfiddle though without the Google Sheets connection.
(I have tried the Google Sheets connection there but it doesn't work -- for reasons yet to be discovered. The connection is public if anyone wants to fiddle.)
So here's the code that I've dumped into the "Custom Code" panel in the "Customize" section of Highcharts Cloud.
Highcharts.addEvent(
Highcharts.seriesTypes.networkgraph, 'afterSetOptions',
function (e) {
var colors = Highcharts.getOptions().colors,
i = 0,
nodes = {};
e.options.data.forEach(function (link) {
if (link[0] === 'Keyword Research') {
nodes['Keyword Research'] = {
id: 'Keyword Research',
marker: { radius: link[2] }
};
nodes[link[1]] = {
id: link[1], marker: { radius: link[2] }, color: colors[i++]
};
}
else if
(nodes[link[0]] && nodes[link[0]].color) {
nodes[link[1]] = {
id: link[1], color: nodes[link[0]].color
};
}
});
e.options.nodes = Object.keys(nodes).map(function (id) { return nodes[id]; });
}
);
Highcharts.chart('highcharts-container',
{
chart: { type: 'networkgraph', height: '100%' },
title: { text: 'The Indo-European Language Tree' },
subtitle: { text: 'A Force-Directed Network Graph in Highcharts' },
plotOptions: { networkgraph: { keys: ['from', 'to'], layoutAlgorithm: { enableSimulation: true, friction: -0.9 } } },
series: [{
dataLabels: { enabled: true, linkFormat: '' },
"data": {
"googleSpreadsheetKey": "1kQKkN4auaxsgwms057FkJ7l5g3mhBjR5vp5PPpStDBQ",
"dataRefreshRate": false,
"enablePolling": true,
"startRow": "2",
"endRow": "14",
"startColumn": "1",
"endColumn": "3"
}
}]
}
);
It'd be great to find out how to make it work.
LATER
Setup for GoogleDrive included as a comment in the jsfiddle.
I have not solved this 100%, but have fixed one issue which may lead you to get an answer. You have your data element inside series, but when looking at the highcharts api for googleSpreadsheetKey, they have put it outside series. So, try the following. When I do, I get CORS error in the console.
Highcharts.addEvent(
Highcharts.seriesTypes.networkgraph, 'afterSetOptions',
function (e) {
var colors = Highcharts.getOptions().colors,
i = 0,
nodes = {};
e.options.data.forEach(function (link) {
if (link[0] === 'Keyword Research') {
nodes['Keyword Research'] = {
id: 'Keyword Research',
marker: { radius: link[2] }
};
nodes[link[1]] = {
id: link[1], marker: { radius: link[2] }, color: colors[i++]
};
}
else if
(nodes[link[0]] && nodes[link[0]].color) {
nodes[link[1]] = {
id: link[1], color: nodes[link[0]].color
};
}
});
e.options.nodes = Object.keys(nodes).map(function (id) { return nodes[id]; });
}
);
Highcharts.chart('highcharts-container',
{
chart: { type: 'networkgraph', height: '100%' },
title: { text: 'The Indo-European Language Tree' },
subtitle: { text: 'A Force-Directed Network Graph in Highcharts' },
plotOptions: { networkgraph: { keys: ['from', 'to'], layoutAlgorithm: { enableSimulation: true, friction: -0.9 } } },
series: [{
dataLabels: { enabled: true, linkFormat: '' }
}],
"data": {
"googleSpreadsheetKey": "1kQKkN4auaxsgwms057FkJ7l5g3mhBjR5vp5PPpStDBQ",
"dataRefreshRate": false,
"enablePolling": true,
"startRow": "2",
"endRow": "14",
"startColumn": "1",
"endColumn": "3"
}
});
Highcharts Cloud doesn't support force directed graph for now.
This series requires network graph module (https://code.highcharts.com/modules/networkgraph.js) which is not imported for charts created in Cloud. Here's the list of imported scripts:
var scripts = [
"highcharts.js",
"modules/stock.js",
"highcharts-more.js",
"highcharts-3d.js",
"modules/data.js",
"modules/exporting.js",
"modules/funnel.js",
"modules/solid-gauge.js",
"modules/export-data.js",
"modules/accessibility.js",
"modules/annotations.js"
];

Highcharts - Sunburst Module - series.data : Same var but one work, the other one not

I'm struggling with a very strange problem using Highcharts Sunburst.
Before all, keep in mind that I've validate my JSON and test it in the JSFiddle demo (find in the documentation), everything works fine.
Here's my problem :
I get my data like that :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var chart_data = parsed_data.data;
( My JSON look like : {data: [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]} )
If a used chart_data in the chart constructor, no chart, no error.
If I set my var this way :
var data = [{id: "0", parent: "", name: " ", desc: " ", value: " "},...]};
And use it in the chart constructor, everything works fine.
I was thinking it could come from my graph options so I copy/paste the one from JSFiddle, still not working...
Here's my complete chart generation code :
var data = sessionStorage.getItem('data_fap');
var parsed_data = JSON.parse(data);
var new_data = parsed_data.data;
// Splice in transparent for the center circle
Highcharts.getOptions().colors.splice(0, 0, 'transparent');
Highcharts.chart('graph_metier', {
chart: {
height: '100%'
},
title: {
text: 'Domaines et familles professionnels'
},
subtitle: {
text: ''
},
series: [{
type: "sunburst",
data: new_data,
allowDrillToNode: true,
cursor: 'pointer',
dataLabels: {
format: '{point.name}',
filter: {
property: 'innerArcLength',
operator: '>',
value: 16
}
},
levels: [{
level: 1,
levelIsConstant: false,
levelSize: {
unit: 'percentage',
value: 30
}
},{
level: 2,
colorByPoint: true
},
{
level: 3,
colorByPoint: true
}]
}],
plotOptions: {
series: {
events: {
click: function (event) {
if(event.point.parent != "0"){
}
}
}
}
},
tooltip: {
formatter: function(e){
if(e.chart.hoverPoint.options.id == 0){
return false;
}
else
{
return '<b>' + e.chart.hoverPoint.options.name + '</b> (code: ' + e.chart.hoverPoint.options.id + ')<br>' + e.chart.hoverPoint.options.desc;
}
}
}
});
If anyone could help me to understand this mess, I'll be infinitely grateful :)

Custom Map in Datamaps

Hello I'm using d3 js with datamaps and I want to show the few countries of the world. I have checked the online forum for the help but not get cleared idea or response.
Source code :
<div id="container" style="position: relative; width: 900px; height: 500px;"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="http://datamaps.github.io/scripts/0.4.4/datamaps.world.min.js"></script>
<script>
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(0,0,0)',
defaultFill: 'green'
},
dataType: 'json', //for use with dataUrl, currently 'json' or 'csv'. CSV should have an `id` column
dataUrl: null,
geographyConfig: {
dataUrl: null, //if not null, datamaps will fetch the map JSON (currently only supports topojson)
hideAntarctica: true,
borderWidth: 1,
borderOpacity: 1,
borderColor: '#FDFDFD',
popupTemplate: function(geography, data) { //this function should just return a string
return '<div class="hoverinfo"><strong>' + geography.properties.name + '</strong></div>';
},
popupOnHover: true, //disable the popup while hovering
highlightOnHover: true,
highlightFillColor: '#FC8D59',
highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
highlightBorderWidth: 2,
highlightBorderOpacity: 1
},
done: function(datamap) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
console.log(geography);
var url = window.location.href;
var arr = url.split("/");
var result = arr[0] + "//" + arr[2]
window.open(result+'/countries/view/'+geography.properties.name);
});
}
});
</script>
It'll display all the countries. but i want to show few country.
How can I pass the country list over there?
I think with the help of custom.json or topojson. I don't know. Let me know if you have any solution or guidance.

Categories

Resources