[GIS] GeoJSON Layer Order In Leaflet 0.7.5

javascriptlayersleafletorderz-index

I am developing a web application that brings in a number of tileLayers and geoJSON layers. For the tile layers I have been able to do similar to this JSFiddle in that the layers appear depening on their zIndex value regardless of which layer was called in last.

I thought I would be able to do the same for geoJSONS, however when i add/ remove the layers, the last layer that is added in appears on the top, despite which order they have been written in.

After checking through the documentation I am to understand that the zIndex parameter only applies to tileLayers and at least in version 0.7.5 cannot be used with geoJSON.

I have read that a potential workaround is to use the bringToFront/Back() method, however this does not appear to work and I can't imagine will provide the best solution for reading in a large amount of geoJSONS.

If there is no official method with 0.7.5 is there at least a workaround? I have been bringing in the geoJSONS as below.

var testLayer = new L.geoJson(json_testdata, {
style: testStyle
});
testLayer.addData(json_testdata);

Update: This is a JSFiddle that shows the tileLayers working with a ZIndex, however when the GeoJSON layers are added and removed the last one to be added goes on top. Is it possible to maintain the layers position? i.e. the order it is written or assigning an equivalent to a ZIndex?

Best Answer

As Thomas and nathansnider pointed out in the comments, vector layers are limited in terms of manipulation of stack order because of the use of SVG rendering in Leaflet 0.7.x.

But basically, SVG renders the vectors the way they are in the DOM, and bringToFront/Back() do nothing else than appending/prepending the paths within the DOM.

If you are ready to fiddle with Leaflet internal objects, it should then be possible to insert your vectors in the desired position.

Demo: https://jsfiddle.net/x36qkk3c/8/

The demo emulates the use of "zIndex" to re-order vectors. Since it is built on top of your example, it uses the ID to determine a zIndex.

You could optimize the sorting algorithm so that it is faster for big collections of features. You could even consider making a small plugin to help other people facing a similar need.