[GIS] Leaflet – Hide marker before zoom shows marker

leafletmarkerszoom

I have a few thousand markers which are grouped in feature groups which i show depending on the zoom level. At the moment i run the the show/hide function for each feature group after the event zoom end.
But when i'm going from a close zoom level to a smaller one, a few hundrets markers will be shown for a few milliseconds until my function hides them. That's because leaflet shows them before i can hide them with the zoomend event.
This behaviour results in a lag for mobile devices.

What can I do to first run the "Hide/show function" before leaflet shows them all?

Best Answer

Not exactly sure what you implemented with your show/hide function on zoom end, but if you want to prevent showing too many Markers on zoom out, you could use a clustering plugin (typically Leaflet.markercluster).

By default that plugin will hide Markers (and its Clusters) which are "too far from the viewport", which in the case of mobile devices, is set to anything outside the current viewport (see removeOutsideVisibleBounds option). As a consequence, during a zoom (especially visible during zoom out) or pan, newly visible areas will not be populated, until the user releases their pinch, at which point the map "zoomend" event is triggered, giving you a chance to swap your Groups. If you do not do anything special, the plugin will re-populate the viewport with the missing Markers and Clusters of the newly visible areas.

Another option of that plugin is to prevent it from clustering past some zoom level: disableClusteringAtZoom. This will prevent it from displaying its Clusters, so that you retrieve your individual Markers, and still benefit from the above behaviour of removeOutsideVisibleBounds option.