1
votes

I'm using an approach to create a 'map sandwich' whereby I have a basemap, an overlay layer, and then another tile layer (labels) on top (in a new pane).

The problem comes when I try to toggle the labels in a layer control. I can toggle off the layer just fine. However, when I try to re-add the labels, they appear underneath the overlay layer.

It seems like the layer control should remember to put layers back in the same order. Regardless, is there any workaround?

Here is a JSFiddle which recreates the problem concisely. Fiddle Layer Control Problem

var mbstyle = L.mapbox.tileLayer('statecodemog.aa380654');

var mblabels = L.mapbox.tileLayer('statecodemog.798453f5', {
'clickable': 'false'
});

var map = L.map("map", {
zoom: 8,
center: [39, -104.8],
minZoom: 4,
layers: [mbstyle]
});

//create map sandwich
var topPane = map._createPane('leaflet-top-pane', map.getPanes().mapPane);
var topLayer = mblabels.addTo(map);
topPane.appendChild(topLayer.getContainer());

var baseLayers = {
"Mapbox: Contrast Base": mbstyle
};

var groupedOverlays = {
"Labels and Borders": mblabels
};

L.control.layers(baseLayers, groupedOverlays).addTo(map);

var circle = L.circle([39, -104.8], 200000, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map);
1

1 Answers

4
votes

Put explicit zIndexes on your mbstyle and mblabels layers:

var mbstyle = L.mapbox.tileLayer('statecodemog.aa380654', {
    'zIndex': 1
});

var mblabels = L.mapbox.tileLayer('statecodemog.798453f5', {
    'clickable': 'false',
    'zIndex': 1000
});

Then tell your L.control.layers not to mess around with the zIndexes:

L.control.layers(baseLayers, groupedOverlays, {
    'autoZIndex': false
}).addTo(map);

A working fork of your Fiddle: http://jsfiddle.net/r01mmfse/

You can even throw out your mapsandwich part:

//create map sandwich
var topPane = map._createPane('leaflet-top-pane', map.getPanes().mapPane);
var topLayer = mblabels.addTo(map);
topPane.appendChild(topLayer.getContainer());

Another fork of your Fiddle: http://jsfiddle.net/b8439d32/

L.TileLayer reference: http://leafletjs.com/reference.html#tilelayer

L.control.layers reference: http://leafletjs.com/reference.html#control-layers