I'm building a cycle touring map in leaflet.js, with subjective information overlaid as markers, along the lines of "this is a great road", "this town is quite nice" etc. To avoid information overload, I want to only show the most prominent markers at a given zoom level (eg, show awesome roads highlighted at zoom 9, good roads at 11, and all road information, including negative comments, at 13+)
I have two questions here:
-
Is there a recognised idiom or design pattern for this kind of thing? I'm quite happy to manually decide the prominence of each marker, so I don't need any kind of clustering algorithm. There'll be maybe a couple of hundred for the whole state, so it's manageable.
-
How can I implement this in Leaflet? My obvious thought is to attach a handler to map.zoomend() and simply show or hide the relevant markers. Is there a better way?
Best Answer
I think there is no better way than to handle
zoomend
event. To group markers by zoom levels, useL.LayerGroup
: turning them on and off will be easier.Calling
map.removeLayer()
ormap.addLayer()
twice won't produce any errors or add a layer twice: there is an internal hash that prevents such things. So you can just have a bunch ofif (zoom > 6 && zoom <= 10 ) map.addLayer(zoom6_10); else map.removeLayer(zoom6_10);
in the event handler.