Leaflet JS中如何将添加的L.divIcon标记移至已有图层后方?
解决Leaflet中divIcon标记始终显示在图层前方的问题
这个问题我之前也碰到过,核心原因是Leaflet的DOM容器(pane)层级机制:默认情况下,Marker(包括用L.divIcon创建的标记)会被放到markerPane容器里,这个容器的z-index是600;而你的LayerFeatureGroup这类矢量图层会被放到overlayPane容器里,它的z-index只有400。不管你怎么调用bringToBack()或者bringToFront()调整FeatureGroup的顺序,这两个pane的层级差已经决定了Marker会始终显示在矢量图层前面。
下面是具体的解决步骤和修改后的代码:
步骤1:创建自定义低层级pane
先给地图创建一个自定义的pane,设置它的z-index比overlayPane更低,这样里面的内容会被矢量图层覆盖:
// 创建自定义pane,z-index设为350(比overlayPane的400低) map.createPane('lowLayerPane'); map.getPane('lowLayerPane').style.zIndex = 350;
步骤2:将Marker指定到自定义pane
在创建Marker的时候,通过pane选项把它放到我们刚创建的自定义pane里:
var LabelMarker = new L.Marker( [centerPoint.geometry.coordinates[0], centerPoint.geometry.coordinates[1]], { icon: L.divIcon({ className: 'roof-center-label', roofId: currentLayer._leaflet_id, html: PanelNumber, iconAnchor: [0, 0], iconSize: null, popupAnchor: [0, 0] }), // 指定marker使用自定义的低层级pane pane: 'lowLayerPane' } )
完整修改后的代码
var LayerFeatureGroup = new L.FeatureGroup(); var LabelCount = new L.FeatureGroup(); map.addLayer(LayerFeatureGroup); map.addLayer(LabelCount); // 新增:创建自定义pane并设置层级 map.createPane('lowLayerPane'); map.getPane('lowLayerPane').style.zIndex = 350; var LabelMarker = new L.Marker( [centerPoint.geometry.coordinates[0], centerPoint.geometry.coordinates[1]], { icon: L.divIcon({ className: 'roof-center-label', roofId: currentLayer._leaflet_id, html: PanelNumber, iconAnchor: [0, 0], iconSize: null, popupAnchor: [0, 0] }), pane: 'lowLayerPane' // 指定到自定义pane } ) LabelMarker.addTo(LabelCount); // 现在不需要再调用bringToBack(),因为pane层级已经确保它在后面了 // LabelCount.bringToBack();
额外说明
- 如果之后你需要调整这个标记的层级,直接修改自定义pane的
z-index值即可,不用再操作FeatureGroup的顺序。 - 如果你希望部分Marker保持在前面,部分在后面,可以创建多个不同z-index的自定义pane来区分。
内容的提问来源于stack exchange,提问作者user8435607
相关产品推荐
相关产品推荐

