stevage / map-gl-utils

A utility library that makes Mapbox GL JS or Maplibre GL a bit more convenient to work with.
https://npmjs.com/package/map-gl-utils
212 stars 24 forks source link

Make idempotent add/update layer style functions #25

Closed stevage closed 3 years ago

stevage commented 3 years ago

Not sure what these would be called exactly, but it would be really convenient to have one function which defines a layer or source, and can be repeatedly called when values change.

Syntax maybe something like:

map.U.lineLayer('myline', 'mysource', {
...
});

So the first time it creates the layer. Subsequent calls just apply all the properties individually.

stevage commented 3 years ago

Some tricky considerations:

stevage commented 3 years ago

Actually, I'm going to be even bolder:

addLineLayer() etc will now be idempotent, so this simply adds a layer, then changes the definition of that layer:

map.U.addCircleLayer('mycircles', 'mysource', { circleStrokeColor: 'red' });
// if the layer already exists, calling add*Layer simply updates any of the properties
map.U.addCircleLayer('mycircles', 'mysource', { circleStrokeColor: 'red', circleRadius: 4, filter: ['==', 'type', 'active'});

And the same goes for addGeoJSON etc:

map.U.addGeoJSON('mysource');
map.U.addGeoJSON('mysource', geojson);

I think this is going to make working with layers a lot less painful, and remove a lot of race conditions, annoying warnings about "source already exists" etc.

Instead of having to write one set of code that creates layers, and another set that updates specific properties, you can just write one function that defines all the layers (as a function of application state), and call that whenever application state changes.

(It turned out to be pretty easy to write using map.setStyle().)