How to create a map chart in ReactJS using Highcharts
I recently had to create a map chart using Highcharts. There several small issues that I encountered while doing so. The solutions for each individual issue were quite easy to find but I wanted to provide a single solution to implement maps in react-highcharts-official.
Demo: https://codesandbox.io/s/highcharts-react-simple-chart-ftcz3
Step 1: Install packages
npm install highcharts highcharts-react-official @highcharts/map-collection proj4
Step 2: Import packages into your project
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import highchartsMap from "highcharts/modules/map";
import proj4 from "proj4";
import mapDataIE from "@highcharts/map-collection/countries/ie/ie-all.geo.json";
I used a map of Ireland for my demo hence the importing of mapDataIE from the Highcharts map collection. You can find all of the available map collections here
Step 3: Add proj4
Proj4 is needed to draw bubbles on the map. Without it you will encounter the beautiful Highcharts error #21
if (typeof window !== "undefined") {
window.proj4 = window.proj4 || proj4;
}
Step 4: Create options for map
My chart contained a base map with an outline of Ireland along with some bubbles in random locations for demonstration purposes. There are many more options available in Highcharts, check out the API documentation for more.
const mapOptions = {
chart: {
map: 'countries/ie/ie-all'
},
title: {
text: 'Map Demo'
},
credits: {
enabled: false
},
mapNavigation: {
enabled: true
},tooltip: {
headerFormat: '',
pointFormat: '<b>{point.freq}</b><br><b>{point.keyword}</b> <br>lat: {point.lat}, lon: {point.lon}'
},
series: [{
// Use the gb-all map with no data as a basemap
name: 'Basemap',
mapData: mapDataIE,
borderColor: '#A0A0A0',
nullColor: 'rgba(200, 200, 200, 0.3)',
showInLegend: false
}, {
// Specify points using lat/lon
type: 'mapbubble',
name: 'Cities',
color: '#4169E1',
data: [{ z: 10, keyword: "Galway", lat: 53.27, lon: -9.25 },
{ z: 4, keyword: "Dublin", lat: 53.27, lon: -6.25 }],
cursor: 'pointer',
point: {
events: {
click: function() {
console.log(this.keyword);
}
}
}
}]
}
Step 5: Initialize the model
I placed this line just below my imports.
highchartsMap(Highcharts);
Step 6: Put it all together
Pass the options to your component and voila you have a map chart.
We pass ‘mapChart’ as the constructor type so that Highmaps is used rather than Highcharts.
<HighchartsReact
constructorType ={'mapChart'}
highcharts={Highcharts}
options={mapOptions}
/>