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.
JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)
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
iframe
As a ES2015 class, that gets expressed like so:
1 | import mapboxgl from 'mapbox-gl'; |
And I can instantiate it like this:
1 | // Create map |
And…done. What if I want to change the breaks?
1 | 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.
Note you’ll have to use something like Babel to transform the JavaScript to something browsers can understand. But with classes and a bunch of other ES2015 features at your fingertips, you should be using Babel anyway.