[GIS] Custom ordering/z-index of icons in Leaflet layer

javascriptleafletweb-mapping

I have a single layer (points) with a bunch of markers. Each point has an attribute that is regularly updated. I understand by Leaflet sorts the layers such that those lower in latitude are on top for aesthetic reasons, but I would like to reorder them such that in areas of clustering, those with higher values in the attribute are on top. Is there any way to do this without having to split up each marker/point into an individual layer and forcing draw order that way?

Best Answer

Until somebody finds a better solution, here what I would do ...

As you noticed, leaflet is using pixel position to set zIndex (in Marker.js)

pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
this._zIndex = pos.y + this.options.zIndexOffset;

What I suggest is to undo leaflet zIndex using setZIndexOffset()

Say you want to set zIndex = 100, you would do

var pos = map.latLngToLayerPoint(marker.getLatLng()).round();
marker.setZIndexOffset(100 - pos.y);

There is a bit of a glitch: you have to do it every time the map is zoomed :(

Here is a JSFiddle example (comment the code in adjustZindex() to see the difference)

Related Question