TopoJSON in Highcharts Maps


Blog Posts Highmaps Tutorials0 comments

Featured image

 

 
Highcharts Maps has built-in support for GeoJSON, a format for defining map shapes and features. A popular extension of GeoJSON is TopoJSON. In TopoJSON, repetetive path segments are extracted and defined only once, and then referenced from the geometries. This makes the file size smaller and better suited for loading in web pages. For example, imagine a map with two neighboring countries. In GeoJSON, the border segment would be repeated for the outline of each of the countries. In TopoJSON this segment is extracted and referenced from both countries.

Map data

If you don’t have your own TopoJSON files, there are some collections available on GitHub. One of them is TopoJSON Collection, where the author has picked map sources that are believed to be licensed for reuse or which are in the public domain. For our demo we will use a Europe map from another provider, leakyMirror, served through jsDelivr.

Convert into GeoJSON

In order to use TopoJSON in Highcharts Maps, we must first decode it to GeoJSON. This is very simple using the TopoJSON Client library. In this case, we extract the map of Europe which is encoded into topology.objects.europe.

 // Convert the topoJSON feature into geoJSON
const geojson = window.topojson.feature(
    topology,
    topology.objects.europe
);

Now we have a geojson variable that we can apply directly into Highcharts Maps’ chart.map option.

Projection

However that doesn’t look good out of the box. Especially for areas of lower latitudes, the map is distorted. We want to apply a projection using Proj4.js, an MIT licensed JavaScript library. In the demo we have written a helper function that translates the GeoJSON geometries into projected coordinates. Europe looks good using a Lambert Conformal Conic projection, with a projection center in the middle of the area. Projection of all the points in a geojson typically takes 20-30 ms depending on the resolution of the map, so if client-side performance is crucial, you should consider doing this on the server side.

// Apply a Lambert Conformal Conic projection to the GeoJSON
project(
    geojson,
    '+proj=lcc +lat_1=43 +lat_2=62 +lat_0=30 +lon_0=10'
);

 

Putting it together

In the final result we have a nice, projected map. In the sample we use an array of random numbers as the data values, and set joinBy to null to apply it to the countries. In a real world chart we would set joinBy to link the data to the map using one of the GeoJSON/TopoJSON identifier properties, like name, FIPS or HASC.

Consent for marketing cookies needs to be given to post comments