Layer stacking and order
Quick answer
This tutorial explains that draw order in OpenLayers comes from both array position and zIndex, and that zIndex wins whenever layers differ. It builds a stack from ol.layer.Tile, ol.layer.Vector and a label layer, then covers setZIndex, setVisible, setOpacity, setExtent and ol.layer.Group opacity multiplication. It also shows a base map switcher that removes the previous base instead of toggling visibility. Readers can control stacking predictably and debug layers that refuse to appear on top.
Key points
- Set explicit zIndex values instead of relying on insertion order when mixing raster and vector.
- Use ol.layer.Group to toggle visibility and opacity for a whole thematic set at once.
- Remove the old base layer on switch rather than leaving hidden tile layers scheduled.
Example
var base = new ol.layer.Tile({
source: new ol.source.OSM(),
zIndex: 0
});
var parcels = new ol.layer.Vector({
source: new ol.source.Vector({ url: '/data/parcels.geojson', format: new ol.format.GeoJSON() }),
zIndex: 10,
opacity: 0.85
});
var labels = new ol.layer.Vector({
source: labelSource,
zIndex: 20,
declutter: true
});
var map = new ol.Map({
target: 'map',
layers: [base, parcels, labels],
view: new ol.View({
center: ol.proj.fromLonLat([116.397, 39.908]),
zoom: 12
})
});map.getLayers().insertAt(0, highlightLayer); // 数组最前面
highlightLayer.setZIndex(5); // 但 zIndex 更大,画在最上面
map.getLayers().forEach(function (layer) {
if (layer !== highlightLayer) {
layer.setZIndex(layer.getZIndex() + 1);
}
});
highlightLayer.setZIndex(100);
Notes
- Group opacity multiplies with child opacity, so 0.6 over 0.5 renders at 0.3.
- insertAt(0, layer) does not raise a layer whose zIndex is lower than its peers.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Layer stacking and order. https://www.jingweizhi.com/en/openlayers/tutorials/layer-order.html (accessed 2026-11-03).