当我单击它时,如何在顶部设置叠加层



我有一个Openlayers地图,上面有很多叠加层(点坐标(。 这些叠加层通常彼此非常接近或重叠

当我单击现有叠加层时,我希望将叠加层设置在顶部,以便完全看到它,而不是在任何其他叠加层后面。

到目前为止,我只看到可以使用z 索引设置图层。是否也可以使用叠加层来做到这一点?

我想做这样的事情:

map.setLayerIndex(markers, 99);

但有叠加

叠加是控件,它们位于坐标上,而不是固定位置。它们基本上只不过是常规的htmldiv元素并随地图改变位置。

这也意味着,您可以应用普通的CSS样式并在它们上使用z-index

var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
// Vienna marker
var marker1 = new ol.Overlay({
position: ol.proj.fromLonLat([16.3725, 48.208889]),
positioning: 'center-center',
element: document.getElementById('marker1'),
stopEvent: false,
className: 'm1 ol ol-overlay-container ol-selectable'
});
map.addOverlay(marker1);
marker2 = new ol.Overlay({
position: ol.proj.fromLonLat([23.3725, 48.208889]),
positioning: 'center-center',
element: document.getElementById('marker2'),
stopEvent: false,
className: 'm2 ol ol-overlay-container ol-selectable'
});
map.addOverlay(marker2);

function clicked(selector) {
console.log('clicked overlay', selector);
document.querySelectorAll(".ol").forEach(function(el){ 
el.classList.remove('active');
});
document.querySelector(selector).classList.add('active');
}
html, body, .map {
min-height: 50px;
min-width: 50px;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.marker {
width: 30px;
height: 30px;
border: 1px solid #088;
border-radius: 15px;
background-color: #0FF;
}
.m1 .marker {
background-color: #FF0;
}
.active {
z-index: 1234782904789;
}
.active .marker {
background-color: red;
}
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@main/dist/en/v7.0.0/legacy/ol.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@main/dist/en/v7.0.0/legacy/ol.js"></script>
<div id="map" class="map"></div>
<div id="marker1" title="Marker" class="marker" onclick="clicked('.m1')"></div>
<div id="marker2" title="Marker" class="marker" onclick="clicked('.m2')"></div>

现有答案有效,但它不保留叠加层的 z 顺序,它只保证点击的叠加层位于顶部。由于它是此堆叠上下文中唯一具有 z 索引的元素,因此其他元素的 z 顺序将是随机的。

这是一个解决方案,它将点击的叠加层放在前面,同时保留所有其他叠加层的当前 z 顺序:

export function bringToFront (map: PluggableMap, clickedOverlayElement: HTMLElement) {
const overlays = map.getOverlays().sort(zIndexComparator);
overlays.forEach((overlay, i) => {
const element = overlay.get('element');
const container = pointInfo.closest('.ol-overlay-container') as HTMLElement;
container.style.zIndex = element === clickedOverlayElement ? overlays.length.toFixed() : i.toFixed();
});
}
function getOverlayContainer (overlay: Overlay) {
return overlay.get('element').closest('.ol-overlay-container') as HTMLElement;
}
function zIndexComparator (a: Overlay, b: Overlay) {
return (getOverlayContainer(a).style.zIndex > getOverlayContainer(b).style.zIndex)
? 1
: -1;
}

只需在单击叠加元素时调用bringToFront()函数即可。

最新更新