How to use this highchart map in reactJS - javascript

For the past couple days, I was struggling to use this highchart map type in my react project
https://jsfiddle.net/26tbkjov//
Can some one please help me out?
Please check what I achieved until now:
https://codesandbox.io/s/highcharts-react-demo-0m5ux
I am using those highcharts npm packages
"highcharts": "^7.1.2",
"highcharts-react-official": "^2.2.2",
I have tried many things and ended up in a dead path.. the following is the last thing i have tried:
import React from "react";
import mapData from '../../api/mapData';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
require('highcharts/modules/map')(Highcharts);
class MyMap extends React.Component {
constructor(props) {
super(props);
this.state = {
mapValues: [],
modalClassic: false,
};
this.mapData = new mapData();
// preparing the config of map with empty data
this.options = {
title: {
text: 'Widget click by location',
style: {
color: '#fff'
},
},
chart:{
backgroundColor: 'transparent',
type: 'map',
map: null,
},
mapNavigation: {
enabled: true,
enableButtons: false
},
credits: {
enabled: false
},
colorAxis: {
dataClasses: [
{
from: 1,
color: '#C40401',
name: 'widget name one'
}, {
from: 2,
color: '#0200D0',
name: 'widget name two'
}
]
},
tooltip: {
pointFormatter: function() {
return this.name;
}
},
legend: {
align: 'right',
verticalAlign: 'top',
x: -100,
y: 70,
floating: true,
layout: 'vertical',
valueDecimals: 0,
backgroundColor: ( // theme
Highcharts.defaultOptions &&
Highcharts.defaultOptions.legend &&
Highcharts.defaultOptions.legend.backgroundColor
) || 'rgba(255, 255, 255, 0.85)'
},
series: [{
name: 'world map',
dataLabels: {
enabled: true,
color: '#FFFFFF',
format: '{point.postal-code}',
style: {
textTransform: 'uppercase'
}
},
tooltip: {
ySuffix: ' %'
},
cursor: 'pointer',
joinBy: 'postal-code',
data: [],
point: {
events: {
click: function(r){
console.log('click - to open popup as 2nd step');
console.log(r);
}
}
}
}]
};
}
/*
* Before mounting the component,
* update the highchart map options with the needed map data and series data
* */
componentWillMount = () => {
this.mapData.getWorld().then((r)=>{
this.setState({'mapData': r.data}, ()=>{
this.options.series[0].data = []; //make sure data is empty before fill
this.options['chart']['map'] = this.state.mapData; // set the map data of the graph (using the world graph)
// filling up some dummy data with values 1 and 2
for(let i in this.state.mapData['features']){
let mapInfo = this.state.mapData['features'][i];
if (mapInfo['id']) {
var postalCode = mapInfo['id'];
var name = mapInfo['properties']['name'];
var value = i%2 + 1;
var type = (value === 1)? "widget name one" : "widget name two";
var row = i;
this.options.series[0].data.push({
value: value,
name: name,
'postal-code': postalCode,
row: row
});
}
}
// updating the map options
this.setState({mapOptions: this.options});
});
});
}
render() {
return (
<div>
{(this.state.mapData)?
<HighchartsReact
highcharts={Highcharts}
constructorType={'mapChart'}
options={(this.state.mapOptions)? this.state.mapOptions: this.options}
/>
: ''}
</div>
);
}
}
export default MyMap;

If you want to use the USA map, you need to change the url to: "https://code.highcharts.com/mapdata/countries/us/us-all.geo.json" and the postal-code from US.MA to MA:
this.mapData.getWorld().then(r => {
...
for (let i in this.state.mapData["features"]) {
...
var postalCode = mapInfo.properties["postal-code"];
...
}
...
});
Live demo: https://codesandbox.io/s/highcharts-react-demo-jmu5h
To use the word map, you need to also change the part related with the postal-code and joinBy property:
series: [{
joinBy: ['iso-a2', 'code'],
...
}]
this.mapData.getWorld().then(r => {
...
for (let i in this.state.mapData["features"]) {
let mapInfo = this.state.mapData["features"][i];
if (mapInfo["id"]) {
var code = mapInfo["id"];
...
this.options.series[0].data.push({
"code": code,
...
});
}
}
...
});
Live demo: https://codesandbox.io/s/highcharts-react-demo-sxfr2
API Reference: https://api.highcharts.com/highmaps/series.map.joinBy

Related

Is it possible to have just one custom datalabel on a stacked waterfall with Highcharts?

I am using the react wrapper for high charts btw.
What I have currently.
What I'm aiming for with but stacked waterfall chart
Just started using high charts and I love it but this one has me stumped. I figured out the data that I need to put that but now I just need to be able to place it in there..
Possible avenues of approach:
Is there a way to add custom HTML only for the top series?
Could I alter the data set to maybe re-render with the top label?
Could I just make the labels show but add an additional label above with the points I wants and make the rest transparent?
import React from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import HC_more from "highcharts/highcharts-more";
HC_more(Highcharts);
let categories = ["bar 1", "bar 2", "bar 3", "bar 4", "total bar"];
let series = [
{
data: [
20,
10,
-15,
30,
{
isSum: true,
},
],
name: "custom series 1",
},
{
data: [
20,
50,
-25,
10,
{
isSum: true,
},
],
name: "custom series 2",
lineWidth: 0,
},
{
data: [
5,
10,
-5,
10,
{
isSum: true,
},
],
name: "custom series 3",
lineWidth: 0,
},
];
let grandTotal = true;
function _createLabelValuePairs(s, c) {
let collection = {};
//Step 0 - iterate over data to get the series
s.map((dataSet) => {
//since we have total bars. Something that shouldn't be calc into the dataset we still need to figure out how many series it has
//for all the set values
dataSet.data.map((item, idx) => {
if (typeof item == "number") {
if (collection[c[idx]]) {
collection[c[idx]]["values"].push(item);
} else {
collection[c[idx]] = {};
collection[c[idx]]["values"] = [];
collection[c[idx]]["values"].push(item);
}
}
});
});
//Step 1 - Get my totals for each dataset
for (const a in collection) {
collection[a]["barTotal"] = collection[a].values.reduce(
(partialSum, a) => partialSum + a,
0,
);
}
//Step 2 - Get grand total numbers of all datasets.
if (grandTotal) {
//Step 2a - Totals for each bar
let sum = 0;
for (const item in collection) {
sum = sum + collection[item].barTotal;
if (collection[c[c.length - 1]]) {
collection[c[c.length - 1]]["values"].push(collection[item].barTotal);
} else {
collection[c[c.length - 1]] = {};
collection[c[c.length - 1]]["values"] = [];
collection[c[c.length - 1]]["values"].push(collection[item].barTotal);
}
}
//grand total bar will be the last entry in the set you pass in
collection[c[c.length - 1]]["barTotal"] = sum;
//Step 2b - Totals for each series
options.series.map((item) => {
if (collection[c[c.length - 1]]["seriesTotal"]) {
collection[c[c.length - 1]]["seriesTotal"][
item["name"]
] = item.data.reduce((partialSum, a) => {
if (typeof partialSum == "number") {
return Number(partialSum) + a;
}
}, 0);
} else {
collection[c[c.length - 1]]["seriesTotal"] = {};
collection[c[c.length - 1]]["seriesTotal"][item["name"]] = 0;
collection[c[c.length - 1]]["seriesTotal"][
item["name"]
] = item.data.reduce((partialSum, a) => {
if (typeof partialSum == "number") {
return Number(partialSum) + a;
}
}, 0);
}
if (
collection[c[c.length - 1]]["seriesTotal"][item["name"]].indexOf(
"[object Object]",
)
) {
collection[c[c.length - 1]]["seriesTotal"][item["name"]] = Number(
collection[c[c.length - 1]]["seriesTotal"][item["name"]].split(
"[object Object]",
)[0],
);
}
});
}
return collection;
}
function _getDelta(key, sets) {
console.log(sets);
//not passing anything back into the datalabel
return null;
}
const options = {
chart: {
type: "waterfall",
className: "test",
showAxes: false,
},
colors: ["#00A9F4", "#B3B3B3", "#000000"],
legend: {
align: "right",
symbolRadius: 0,
verticalAlign: "top",
},
title: {
text: "Stacked waterfall example",
},
plotOptions: {
series: {
stacking: "normal",
},
waterfall: {
borderColor: "none",
dashStyle: "Solid",
dataLabels: {
useHTML: true,
className: "waterfall-label",
enabled: true,
formatter: function(a) {
return _getDelta(
this.key,
_createLabelValuePairs(series, categories),
);
},
inside: false,
},
states: {
hover: {
animation: {
duration: 0,
},
enabled: false,
},
inactive: {
enabled: false,
},
select: {
enabled: false,
},
},
},
},
xAxis: {
categories: categories,
labels: {
style: {
color: "#000000",
cursor: "default",
fontSize: "14px",
fontFamily: "Mckinsey Sans Regular",
width: "75px",
whiteSpace: "normal", //set to normal
},
},
},
yAxis: {
visible: false,
},
series: series,
credits: {
enabled: false,
},
tooltip: {
animation: false,
backgroundColor: "#333333",
borderColor: "inherit",
borderRadius: 0,
formatter: function() {
return this.x + ": " + this.y;
},
hideDelay: 0,
shadow: false,
style: {
color: "white",
},
},
};
function Waterfall() {
return <HighchartsReact highcharts={Highcharts} options={options} />;
}
export default Waterfall;
And if you want to know what all that code was for _createLabelPairs it's just to get the totals of the series and that of the bars as well( If I need to use those later). I can figure out the percentages with barTotals and total property in the total bar
result from _createLabelPairs function

Chart.js legend configuration options not working [duplicate]

I am trying to hide the legend of my chart created with Chart.js.
According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options.display object must be set to false.
I have tried to do it in the following way:
const options = {
legend: {
display: false,
}
};
But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.
const options = {
legend: {
display: false,
labels: {
display: false
}
}
}
};
This is my full code.
import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 1,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,000");
},
},
},
scales: {
xAxes: [
{
type: "time",
time: {
format: "DD/MM/YY",
tooltipFormat: "ll",
},
},
],
yAxes: [
{
gridLines: {
display: false,
},
ticks: {
callback: function(value, index, values) {
return numeral(value).format("0a");
},
},
},
],
},
};
const buildChartData = (data, casesType = "cases") => {
let chartData = [];
let lastDataPoint;
for(let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
.then ((response) => {
return response.json();
})
.then((data) => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
return (
<div>
{data?.length > 0 && (
<Line
data={{
datasets: [
{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data
},
],
}}
options={options}
/>
)}
</div>
);
}
export default LineGraph;
Could someone help me? Thank you in advance!
PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.
const options = {
legend: {
display: true,
text: 'Hello!'
}
};
As described in the documentation you linked the namespace where the legend is configured is: options.plugins.legend, if you put it there it will work:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}
]
},
options: {
plugins: {
legend: {
display: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
On another note, a big part of your options object is wrong, its in V2 syntax while you are using v3, please take a look at the migration guide
Reason why you get undefined as text in your legend is, is because you dont supply any label argument in your dataset.
in the newest versions this code works fine
const options = {
plugins: {
legend: {
display: false,
},
},
};
return <Doughnut data={data} options={options} />;
Import your options value inside the charts component like so:
const options = {
legend: {
display: false
}
};
<Line data={data} options={options} />

Integrate Highcharts maps with react component

I am trying to integrate highcarts inside the react component.
Here is my code for the react component
import * as Highcharts from 'highcharts/highmaps'
class RealTime extends Component {
componentDidMount() {
$.getJSON( 'https://cdn.jsdelivr.net/gh/highcharts/highcharts#v7.0.0/samples/data/world-population-density.json',
function(data) {
$.each(data, function() {
this.value = this.value < 1 ? 1 : this.value
})
Highcharts.mapChart('world_map', {
chart: {
map: 'custom/world'
},
title: {
text: 'Fixed tooltip with HTML'
},
legend: {
title: {
text: 'Population density per km²',
style: {
color:
(Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
series: [
{
data: data,
mapData: Highcharts.maps['custom/world'],
joinBy: ['iso-a3', 'code3'],
name: 'Population density',
states: {
hover: {
color: '#a4edba'
}
}
}
]
})
}
)
}
render() {
return (
<div>
<div className="map_bg" id="world_map"/>
</div>
)
}
}
But the above code does not show either the map or any error in my react component . Can Anyone please help me
What i am missing here?
Thank you!!!
You need to add and import the word.js script:
import Highcharts from "highcharts/highmaps";
import customWord from "./word.js";
Live demo: https://codesandbox.io/s/v0x5zx6q05
Also, I can recommend you to use highcharts-react-official wrapper: https://www.npmjs.com/package/highcharts-react-official

HighCharts. Angular. Redraw Chart with new Series on Event Click

kind of stuck in a hole here. I have a stacked Highchart that I'm trying to re-render when you click on a button. Here is what it looks like for now:
Clicking on any of the buttons will trigger a designated event handler that helps me generate a new series of data for that particular category. The data is organized in a way that bar-charts can consume.
For instance, clicking on the "Asset Class" button will return an output of:
(4) [{…}, {…}, {…}, {…}]
0: {name: "Cash", data: Array(1)}
1: {name: "Equity", data: Array(1)}
2: {name: "Fixed Income", data: Array(1)}
3: {name: "Fund", data: Array(1)}
length: 4
The problem I'm having is that the chart never seems to update even though I'm updating the series data. (this.chart.options.series = myNewSeries)
Some events will return more than 4 items (could be anywhere from 4 to 30 values) and I need them to stack as well.
Here is my code with the updating logic near the bottom:
export class ChartComponent{
constructor(){
|| block of script logic ||
this.options = {
chart: {
type: 'column',
height: 500,
width: 500,
style: {
fontFamily: "Arial"
},
events: {
redraw: function (){
alert("The chart is being redrawn")
}
}
},
title: {
text: ""
},
xAxis: {
categories: this.seriesData.category,
labels: {
style: {
fontSize: "14px"
}
}
},
yAxis: {
min: 0,
title: {
text: ""
},
labels: {
formatter: function () {
let valueString = (
this.value > 999.99 && this.value <= 999999.99 ?
"$" + (this.value / 1000).toFixed(0) + "K" : this.value > 999999.99 ?
"$" + (this.value / 1000000).toFixed(1) + "M" : this.value
)
return valueString
},
style: {
fontSize: "14px",
}
}
},
legend: {
x: 0,
y: 0,
verticalAlign: "top",
align: "right",
layout: "vertical",
itemStyle: {
fontSize: "16px",
color: "#6c6c6c",
},
symbolPadding: 8,
itemMarginTop: 10,
shadow: false,
labelFormatter: function () {
return `${this.name}`
}
},
tooltip: {
formatter: function () {
let name = this.series.name
let value = this.y
let valueString = `$${value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`
let total = this.point.stackTotal
let percentage = ((value / total) * 100).toFixed(2)
let percentageString = `(${percentage})%`
return `<b>${name}</b> <br> ${valueString} ${percentageString}`
},
style: {
fontSize: "14px",
},
backgroundColor: "#ffffff"
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: false
}
},
series: {
pointWidth: 100,
borderColor: "rgba(0, 0, 0, 0)"
}
},
series: this.seriesData.series
}
}
options: Object
saveInstance(chartInstance): void {
this.chart = chartInstance;
}
updateSeriesData = (data: Array<any>, title): void => {
this.chart.options.series = data
this.chart.xAxis[0].update({categories: title})
}
// event handlers
getIndustryData = (e) => {
let newSeries = this.getSeriesTotals("Industry", "SecuritySectorLevel1", "SecuritySectorLevel2")
this.updateSeriesData([...newSeries.series], newSeries.category)
}
getSectorData = (e) => {
let newSeries = this.getSeriesTotals("Sector", "SecuritySectorLevel2", "SecuritySectorLevel1")
this.updateSeriesData([...newSeries.series], newSeries.category)
}
getAssetClassData = (e) =>{
let newSeries = this.getSeriesTotals("Asset Class", "AssetClassLevel1", "SecuritySectorLevel1")
this.updateSeriesData([...newSeries.series], newSeries.category)
}
getRegionData = (e) => {
let newSeries = this.getSeriesTotals("Region", "CountryOfRisk", "CountryOfIssuance")
this.updateSeriesData([...newSeries.series], newSeries.category)
}
getCurrencyData = (e) =>{
let newSeries = this.getSeriesTotals("Currency", "LocalCCY", "LocalCCYDescription")
this.updateSeriesData([...newSeries.series], newSeries.category)
}
}
Generally speaking, for the next person who surfs here:
In your HTML-Element you'll have something like:
<highcharts-chart
...
[(update)]="updateFlag">
</highcharts-chart>
And in the corresponding Typescript file you have a
updateFlag = false;
and after the section where you've changed something, you do:
this.updateFlag = true;

Optimize JavaScript DrillDown code

I have a drilldown map on my page which I would like to optimise.
Right now I am loading every "drilldown" map even if it is not clicked.
Here is an example that shows how the data is load if the state is clicked.I would like to achieve that.
But this is my code and as you can see, I am loading all drilldown jsons even if the map is not clicked. In my example I have only 2 drilldown option, but in my real life problem I have it like 15 so it really slows down a little bit everything.
So this is my code:
// get main map
$.getJSON('json/generate_json_main_map.php', function(data) {
// get region 1 map
$.getJSON('json/generate_json_region_1.php', function(first_region) {
// get region 2 map
$.getJSON('json/generate_json_region_2.php', function(second_region) {
// Initiate the chart
$('#interactive').highcharts('Map', {
title: {
text: ''
},
colorAxis: {
min: 1,
max: 10,
minColor: '#8cbdee',
maxColor: '#1162B3',
type: 'logarithmic'
},
series: [{
data: data,
"type": 'map',
name: st_ponudb,
animation: {
duration: 1000
},
states: {
//highlight barva
hover: {
color: '#dd4814'
}
}
}],
drilldown: {
drillUpButton: {
relativeTo: 'plotBox',
position: {
x: 0,
y: 0
},
theme: {
fill: 'white',
'stroke-width': 0,
stroke: 'white',
r: 0,
states: {
hover: {
fill: 'white'
},
select: {
stroke: 'white',
fill: 'white'
}
}
}
},
series: [{
id: 'a',
name: 'First',
joinBy: ['hc-key', 'code'],
type: 'map',
data: first_region,
point: {
events: {
click: function() {
var key = this.key;
location.href = key;
}
}
}
}, {
id: 'b',
name: 'Second',
joinBy: ['hc-key', 'code'],
type: 'map',
data: second_region,
point: {
events: {
click: function() {
var key = this.key;
location.href = key;
}
}
}
}]
}
});
});
});
});
JSON from generate_json_main_map.php:
[{"drilldown":"a","name":"region 1","value":"1","path":""},{"drilldown":"b","name":"region 2","value":"2","path":""}]
JSON from generate_json_region_1.php:
[{"name":"Place 1","key":"place.php?id=1","value":"1","path":""},{"name":"Place 2","key":"place.php?id=2","value":"2","path":""}]
This is my attempt to make ajax calls load in parallel, but the map is not loading, I get just the coloraxis.
$(function() {
$.when($.getJSON('json/generate_json_main_map.php'), $.getJSON('json/generate_json_region_1.php'), $.getJSON('json/generate_json_region_2.php')).done(function(data,first_region,second_region){
$('#interactive').highcharts('Map', {
title: {
text: ''
},
colorAxis: {
min: 1,
max: 10,
minColor: '#8cbdee',
maxColor: '#1162B3',
type: 'logarithmic'
},
series: [{
data: data,
"type": 'map',
name: st_ponudb,
animation: {
duration: 1000
},
states: {
hover: {
color: '#dd4814'
}
}
}],
drilldown: {
drillUpButton: {
relativeTo: 'plotBox',
position: {
x: 0,
y: 0
},
theme: {
fill: 'white',
'stroke-width': 0,
stroke: 'white',
r: 0,
states: {
hover: {
fill: 'white'
},
select: {
stroke: 'white',
fill: 'white'
}
}
}
},
series: [{
id: 'a',
name: 'First',
joinBy: ['hc-key', 'code'],
type: 'map',
data: first_region,
point: {
events: {
click: function() {
var key = this.key;
location.href = key;
}
}
}
}, {
id: 'b',
name: 'Second',
joinBy: ['hc-key', 'code'],
type: 'map',
data: second_region,
point: {
events: {
click: function() {
var key = this.key;
location.href = key;
}
}
}
}]
}
});
});
});
I can see that the jsons are loaded and there is no JS error shown by firebug.
If you want to load on click, you need to call the state data on click_event (and not at startup).
Just like your JSFiddle example:
chart : {
events: {
drilldown: function (e) {
// Load you data
// show it with chart.addSeriesAsDrilldown(e.point, {...});
}
}
}
Or as #Whymarrh suggests, you can load them all in parallel (instead of one after the other) and once they are all retrieved, compute your map.
See https://lostechies.com/joshuaflanagan/2011/10/20/coordinating-multiple-ajax-requests-with-jquery-when/ for example on how to execute a code after all ajax calls have completed.
When you load your map data as you did, in the following manner:
$.when(
$.getJSON('json/generate_json_main_map.php'),
$.getJSON('json/generate_json_region_1.php'),
$.getJSON('json/generate_json_region_2.php')
).done(...);
The effect is this - when any of the three requests fail, all promises will be rejected and ultimately, your map never gets to be initialised.
A better approach could be to request all data independently, and the outcomes would be handled as follows:
If the request for the main data fails, abort the other requests unconditionally (there would be no need for a drill down if the primary data is non-existent).
If request for main data succeeds, you may go on and initialise the map as data becomes available. The request for drill down data may or may not succeed though (but half bread is better than none?). Assuming everything goes well, then in the event that user initiates a drill down action, you show a loading message and ultimately add the drill down series when it becomes available.
Here's an implementation of the method I offered:
$(function () {
// immediately trigger requests for data
var loadMainData = $.getJSON("json/generate_json_main_map.php");
var loadRegionData = {
"region-1-name": $.getJSON("json/generate_json_region_1.php"),
"region-2-name": $.getJSON("json/generate_json_region_2.php")
};
// region drilldown options
var regionalSeriesOptions = {
"region-1-name": {
id: 'a',
name: 'First',
joinBy: ['hc-key', 'code'],
type: 'map',
point: {
events: {
click: function () {
var key = this.key;
location.href = key;
}
}
}
},
"region-2-name": {
id: 'b',
name: 'Second',
joinBy: ['hc-key', 'code'],
type: 'map',
point: {
events: {
click: function () {
var key = this.key;
location.href = key;
}
}
}
},
// ...
"region-(n-1)-name": {
// series options for region 'n-1'
},
"region-n-name": {
// series options for region 'n'
},
"region-(n+1)-name": {
// series options for region 'n+1'
}
};
// main options
var options = {
title: {
text: ""
},
series: [{
type: "map",
name: st_ponudb,
animation: {
duration: 1000
},
states: {
hover: {
color: "#dd4814"
}
}
}],
events: {
drilldown: function (e) {
var regionName, request, series, chart;
if (e.seriesOptions) {
// drilldown data is already loaded for the currently
// selected region, so simply return
return;
}
regionName = e.point.name;
request = loadRegionData[regionName];
series = regionalSeriesOptions[regionName];
chart = this;
chart.showLoading("Loading data, please wait...");
request.done(function (data) {
// series data has been loaded successfully
series.data = data;
chart.addSeriesAsDrilldown(e.point, series);
});
request.fail(function () {
if (loadMainData.readyState !== 4) {
// do you really want to cancel main request
// due to lack of drilldown data?
// Maybe half bread is better than none??
loadMainData.abort();
}
});
// whether success or fail, hide the loading UX notification
request.always(chart.hideLoading);
}
},
colorAxis: {
min: 1,
max: 10,
minColor: '#8cbdee',
maxColor: '#1162B3',
type: 'logarithmic'
},
drilldown: {
drillUpButton: {
relativeTo: 'plotBox',
position: {
x: 0,
y: 0
},
theme: {
fill: 'white',
'stroke-width': 0,
stroke: 'white',
r: 0,
states: {
hover: {
fill: 'white'
},
select: {
stroke: 'white',
fill: 'white'
}
}
}
},
series: []
}
};
loadMainData.done(function (data) {
options.series[0].data = data;
$("#interactive").highcharts("Map", options);
}).fail(function () {
Object.keys(loadRegionData).forEach(function (name) {
// if primary data can't be fetched,
// then there's no need for auxilliary data
loadRegionData[name].abort();
});
});
});
Since I don't know every detail of your code, it's left for you to find a way to fit it into your solution.

Categories