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.
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
// 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.
// 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' );
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
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.