Skip to content

Instantly share code, notes, and snippets.

@up209d
Last active September 13, 2023 09:31
Show Gist options
  • Save up209d/4c68f2391f2302e510eb81aa8bcd4514 to your computer and use it in GitHub Desktop.
Save up209d/4c68f2391f2302e510eb81aa8bcd4514 to your computer and use it in GitHub Desktop.
Force zIndex of Leaflet Marker
// Force zIndex of Leaflet
(function(global){
var MarkerMixin = {
_updateZIndex: function (offset) {
this._icon.style.zIndex = this.options.forceZIndex ? (this.options.forceZIndex + (this.options.zIndexOffset || 0)) : (this._zIndex + offset);
},
setForceZIndex: function(forceZIndex) {
this.options.forceZIndex = forceZIndex ? forceZIndex : null;
}
};
if (global) global.include(MarkerMixin);
})(L.Marker);
@gpsvisualizer
Copy link

Thanks for this! I was going crazy trying to figure out what I was missing with zIndexOffset. I eventually figured out that it works properly for default Leaflet icons... but as soon as you apply a custom "iconUrl", zIndexOffset becomes unpredictable or doesn't work at all.

Your "setForceZIndex" function does exactly what the standard Leaflet code claims to do, but doesn't.

@Steckelfisch
Copy link

Steckelfisch commented Feb 23, 2022

Thank you very much!!!

I observed the same unpredictable z-index calculation @gpsvisualizer mentioned, bar the proper functionality of the default icons.
After dragging my location-marker a few times arround, the z-index changed from some_large_value to -other_large_value.

Not anymore.

@utilmind
Copy link

utilmind commented Apr 15, 2023

Let me add little fix, to allow forceZIndex = 0. Check whether forceZIndex is assigned with isNaN(). Any numeric should be considered as good value.

    _updateZIndex: function(offset) { // offset at relative value, or put absolute zIndex value with forceZIndex
        this._icon.style.zIndex = isNaN(this.options.forceZIndex) // any no-numeric = unassigned. 0 is ok for the forceZIndex
            ? (this._zIndex + offset)
            : (this.options.forceZIndex + (this.options.zIndexOffset || 0))
    },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment