TopoJSON in Highmaps


Blog Posts Highmaps Tutorials0 comments

Featured image

 

 
Highmaps 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’s a TopoJSON Collection available on GitHub. 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 the US states map, served through jsDelivr.

Convert into GeoJSON

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

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

Now we have a geojson variable that we can apply directly into Highmaps’ 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. The USA looks good using a Lambert Conformal Conic projection, with a projection center in the middle of the country.

// Apply a Lambert Conformal Conic projection to the GeoJSON
project(
    geojson,
    '+proj=lcc +lat_1=33 +lat_2=45 +lat_0=39 +lon_0=-96'
);

 

Performance

While decoding TopoJSON is very fast, applying projection is not. Projecting the USA using LCC  actually takes 400-500ms in our demo. A mercator based projection, like EPSG:3857, is faster but more distorted. So in an optimized production environment it would be better to first apply the projection on the server side, encode the TopoJSON file, send it to the client and let the client decode it into GeoJSON.

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 states. 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
Do NOT follow this link or you will be banned from the site!