10 august 2023
At Nazka Mapps, we wanted to give back to the opensource community. Thus we decided to opensource our inhouse marker spiderfication solution as a MapLibre GL JS plugin. I noticed there aren't any guides available for creating Maplibre plugins, so I had to do my own research. I'd like to share my insights with you here.
Ideally your plugin should extend the core functionalities of MapLibre GL JS without introducing conflicts or inconsistencies. To achieve this you should try to keep your plugin’s interaction with the MapLibre code to an absolute minimum. This will hopefully ensure your plugin won’t break with every new MapLibre release.
Most MapLibre GL JS plugins are build as JS classes. If your plugin will have a map control then going for JS classes is a no brainer. Custom controls in MapLibre are expected to be build as a class with a onAdd and onRemove method. Your plugin could just be a custom control published as an npm package.
// good starting point for a control plugin
class HelloWorldControl {
onAdd(map) {
this._map = map;
this._container = document.createElement('div');
this._container.className = 'maplibregl-ctrl';
this._container.textContent = 'Hello, world';
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
This is just one option as there is no wrong way to structure your plugin’s code. The best approach will often depend on your needs and preferences.
If you need inspiration you can always checkout the approach of other MapLibre plugins.
There are many tutorials that will help you with this. I think this one is a particular helpful one. I recommend using maplibre in your package name as this will help with visibility.
If you have a great idea you should just go for it. Write your code in a way that makes sense to you. Focus on getting a working proof of concept and don’t overthink it as you can always improve it afterwards.
Happy coding!