Leaflet - switching GeoJSON layers without plugins
GeoJSON layers and markers can be used together seamlessly.
To be able to toggle layers, you need to catch some kind of click event from something you can click on, like a button. From my research, I found that if you need a custom button, it is not that fast to implement, so you may need to use one of the plugins available.
If you still don't want to create a button or use a plugin, you can, for example, set a click event on the map itself that turns the GeoJSON layer on and off.
I took the GeoJSON example from the brochure website and modified it to turn the GeoJSON layer on and off:
var geoLayer = L.geoJson([
// ...
]);
map.on('click', function() {
if(map.hasLayer(geoLayer)) {
map.removeLayer(geoLayer);
} else {
map.addLayer(geoLayer);
}
});
Hope it helps.
Edit: I modified this example to use leaflet.js control which is much better ...
var baseLayers = {
"Markers": markerLayer,
"GeoJSON": geoLayer
};
L.control.layers(baseLayers).addTo(map);
Didn't know about it;)
If you want to use checkboxes instead of radio amateurs use instead
L.control.layers(null, baseLayers).addTo(map);
source to share