鼠标移动时,两个图层相互叠加(重叠)



最接近我的问题是:Mapbox gl js -重叠层和鼠标事件处理,Mapbox在悬停(层)上添加弹出窗口,在mouseleave上关闭,但在弹出窗口悬停时保持打开,以及如何忽略Mapbox层上的鼠标事件-但他们不回答它。

我有两层,让我们想象一个是一个国家,另一个是一个城市。它们都是这样处理的:

// CountryLayer.js
map.on("mousemove", "country-layer", e => {
// show info about the country 
featureProps = e.features[0] // display some notification from the props
...
// CityLayer.js
map.on("mousemove", "city-layer", e => {
// show info about the city
featureProps = e.features[0] // display some notification from the props
...

这是在不同的组件中完成的。但是当我将鼠标移到city-layer上时,mapbox认为我仍然在"鼠标移动"。在country-layer之上,所以我从不同的组件得到两个通知,我只需要一个-在这种情况下,来自city-layer,因为它在country-layer之上。

在一个地方处理没有layerId的mousemove将是一个烂摊子,并打破了所有关于编程的好规则。创建外部"事件管理器";这将跟踪我是否在城市悬停,如果是这样,将从country-layer中删除mousemove事件-是复杂的。我没有找到任何好的替代品。至少,我很乐意为这样的图层禁用指针事件:

map.on("mousemove", "city-layer", e => {
map.getLayer("country-layer").setStyle({ "pointer-events": false })
featureProps = e.features[0]
...

之类的。这可能吗?有没有更合适的方法?

e.originalEvent.stopPropagation();不工作

看来,您可以在city-layer中执行e.originalEvent.preventDefault();,并从示例中在country-layer中添加e.originalEvent.defaultPrevented检查。

然而,我对层的z-index位置有问题:map.moveLayer("city-layer", "country-layer");或反之实际上并没有改变方式,事件提议,所以出于某种原因,我的country-layer总是先出现,所以当它检查e.originalEvent.defaultPrevented时,preventDefault()还没有被触发,所以它总是false

但从技术上讲,这回答了我的问题。

map.on可以同时监听多个层。对于像mousemove这样的事件,它以相反的层顺序返回特征(从"最高层"开始)。以"lowest"。

方法是:

map.on("mousemove", ["city-layer", "country-layer"], e => {
feature = e.features[0]
if (feature.layer.id === 'city-layer') {
// ...
} else {
// ...
}
});

最新更新