The Robinson projection in Mapbox GL

We’re open sourcing a way to pre-process geometries for use in Mapbox GL, to produce maps that render something besides the standard Web Mercator projection.

Almost all web mapping libraries render maps using Web Mercator, making an assumption that you generally can’t change out-of-the-box. This has advantages, but it posed a real challenge for us when we set out to build the Washington Post’s live election results map, where using the Albers USA projection was an important requirement. To meet that requirement, we built a pipeline to pre-process geometries.

We started with our standard WGS 84 (longitude/latitude) coordinate geojson files and projected those files into our desired projection. Next, we scaled the result to fit within the Web Mercator coordinate system.

projection

We took the scaled files and reverse-projected them back into WGS 84, before converting them to mbtiles and uploading the whole thing to Mapbox Studio.

projection

We used Mike Bostock’s d3-geo and d3-geo-projection libraries to do the heavy lifting on the rather tricky projection math.

To show some of the projections you can achieve with this method, we built the Dirty Reprojectors App. The site includes the long list of projections d3 comes bundled with, and will also accept and project your own geojson files.

projection

For greater control over projection variables like parallels and center points, use the Dirty Reprojectors CLI instead. There you can tweak the projection code as needed.

Caveats

After reprojecting geometries, the actual longitude/latitude coordinates will not be accurate. This complicates tasks like reverse geocoding.

Actual coordinates are off

Bounds are also tricky. Depending on the projection, a bounding box (rectangle) in longitutde/latitude coordinates may no longer look like one once it’s reprojected. Functions like map.fitBounds() where the map fills the space of its bounds can take more work to get right. Our work-around was to calculate and save the post-projection bounding box for each US state, instead of using the “real” bounding box coordinates.

We’re always looking for novel ways to solve problems. If this helps you solve a problem, we’d love to hear about it. You can always reach out to us on Twitter or Github.