Leaflet - switching GeoJSON layers without plugins

I know how to add a marker layer that I can turn on / off and how to add a layer GeoJSON

to my map.

But I cannot mix these functions.

I need to create toggling layer from GeoJSON

(polyline layer).

Can I get what I need without any external plugins or scripts ?

+3


source to share


1 answer


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);

      

http://codepen.io/anon/pen/qEaEBg

+3


source







All Articles