Put your map in a ES2015 class
Of late I have been leveraging ES2015 classes for my map components. It’s a good thing to do. It started as a side effect of React, but a lot of the niceties are from ES6 classes independent of React.
In other words, they’re pretty and they’re functional. Much better than closures, for which I will forever remember watching Douglas Crockford pointing at the hanging
() and proclaiming “Dog balls!”.
As a bonus, you’re abstracting the mapping library away from your app. This means if you ever decide to move your app to a different mapping backend (spoiler alert: you will), it will be much easier.
For a Print/Embed project tangent to the Quality of Life project, I need to:
- Make a map
- Add a GeoJSON overlay
- Style the overlay
- Highlight specific GeoJSON features
- Report map zoom/center changes to parent if in an
As a ES2015 class, that gets expressed like so:
import mapboxgl from 'mapbox-gl';
And I can instantiate it like this:
// Create map
And…done. What if I want to change the breaks?
map.breaks = newBreaksArray;
It’s a simple and clean way to manage the map, and I could (relatively) easily swap out GL JS for Leaflet and only have to futz with this one class.