leaflet.markercluster - 如何检查标记是否在簇中?

标签 leaflet.markercluster

Leaflet.Markercluster ,如何检查标记是否在集群中?

最佳答案

使用Leaflet的hasLayer()函数

常规可见标记在技术上作为图层存在于 map 中。 Leaflet 还有一个功能 hasLayer()返回 true/false 是否给定的引用(如存储的标记)当前作为图层存在于 map 中(即“可见”)。

针对我的具体问题,我为选定的 map 标记(例如红色边框)提供了特殊的视觉装饰,即使在该标记进出集群后,这种装饰仍然存在。如果所选标记进入集群,我需要它取消选择自身。

下面是粗略的逻辑,它允许我检查给定标记引用在集群事件后是否对用户可见(这可能由于任何原因发生,例如 map 中的缩放事件或非用户驱动的移动)。

相关简码:

我的聚类是这样的...

this.markersClustered = L.markerClusterGroup({ // Lots of stuff here... } })

在我的单个标记的点击事件中,我将标记存储在“selectedItem”对象中(我将其用于我的应用程序中的各种其他逻辑)...

onEachFeature(feature, marker) {
    marker.on("click", e => {

        // ... (lots of code) ...

        // Save instance of the marker; I call it "layer" only
        // because I only use this for the hasLayer() check
        this.selectedItem.layer = marker

        // Here do other stuff too, whatever you need...
        //this.selectedItem.target = e.target
        //this.selectedItem.latlng = e.latlng
        //this.selectedItem.id = e.target.feature.id
        //this.selectedItem.icon = layer._icon

        // ... (lots of code) ...

    })
}

当集群动画结束时,使用 hasLayer(),检查所选标记是否在集群中,然后执行操作。

注意:在我的用例中,检查是在聚类动画结束时完成的,因为我不希望用户看到所选标记在聚类动画发生时失去了它的特殊视觉装饰(它会出现错误) .

this.markersClustered.on('animationend', (e) => {

  // Check visibility of selected marker

  if(this.map.hasLayer(this.selectedItem.layer)) {
      // True: Not in a cluster (ie marker is visible on map)
  } else {
      // False: In a cluster (ie marker is not visible on map)
  }

  console.log("Selected marker visible?:" +  this.map.hasLayer(this.selectedItem.layer))

})

关于leaflet.markercluster - 如何检查标记是否在簇中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57014765/

相关文章:

javascript - 我如何解决此 MarkerCluster checkin / checkout 错误(传单销售人员)?

javascript - Leaflet MarkerCluster - 如何检查集群是否将被蜘蛛化(即具有 maxZoom 级别)?

leaflet - 更改所有标记的拖动状态

leaflet - 在leafletjs中绘制140K点

javascript - 传单标记簇 : How can I create a markercluster with numbered markers?

maps - 将鼠标悬停在集群组上时弹出窗口

由外部元素在集群标记上触发传单事件

javascript - 如何设置MarkerClusterGroup中每个集群的选项

javascript - 传单标记群集标记和群集图标在加载时均可见

javascript - 扩展标记时传单未获取所有数据