如何在 Leaflet MarkerClusterGroup 中为特定标记打开弹出窗口?

3
我希望能在地图缩小时为集群标记下的标记打开弹出窗口。当用户单击搜索结果时,将调用此函数。
这是我正在使用的代码:
map.eachLayer(function (layer) {
    if (layer.options && layer.options.pane === "markerPane") {
        if (layer.options.title == locationId) {
            layer.openPopup()
        }
    }
});

我尝试添加了这段代码,但它也没有起作用:

layer.zoomToBounds({padding: [20, 20]});

这个 map.eachLayer() 调用是在什么时候运行的?只运行一次还是每次 zoomend 事件时都会运行?为什么它是 async 的? - IvanSanchez
当用户点击搜索结果时,将调用此函数。异步是早期版本的剩余物。我现在已经删除它 :) - ShadowRock
你想让弹出窗口在缩小视图时打开,还是当获取搜索结果时打开? - IvanSanchez
当用户点击搜索结果时,我希望弹出窗口打开。当用户点击结果时,会找到位置的ID。使用此ID,我想在地图上打开位置的弹出窗口,包括聚类中的位置。 :) - ShadowRock
2个回答

2

所以,当集群中的特定标记符合条件时,您想要对集群标记执行某些操作。

您可以遍历所有可见的集群标记,然后利用 getAllChildMarkers;但是,这很快就会变得混乱不堪,因为您必须处理集群和集群标记是不同实体的事实,因此遍历可见标记并不一定意味着遍历可见集群。

我建议基于getVisibleParent的方法。存储对每个原始标记的引用,按您稍后用于查找的ID进行索引,例如...

var clusterGroup = L.markerClusterGroup();
var markers = {};   // Yay using Object as a hashmap!
for (var i in dataset) {
    // Create individual marker based on a item in the dataset, e.g.
    var marker = L.marker(dataset[i].latlng);

    // Add that to the clusterGroup (but not to the map)
    clusterGroup.addMarker(marker);

    // Save the individual marker in the hashmap, indexed by the
    // desired property, e.g. "locationId"
    markers[ dataset[i].locationId ] = marker;
}

// Adding the cluster to the map after all items have been inserted should
// be slightly more performant than doing that before.
clusterGroup.addTo(map);

因此,通过期望的ID查找标记应该是可行的,看看它是否在聚类中或直接可见,并对其采取某些措施:

function highlightLocationId(id) {
  // hashmap lookup
  var marker = markers[i];

  // Sanity check
  if (!marker) { return; }

  // What cluster is this marker in?
  var cluster = clusterGroup.getVisibleParent(marker);

  // Is the marker really in a cluster, or visible standalone?
  if (cluster) {
    // It's in a cluster, do something about its cluster.
    cluster.openPopup();
  } else {
    // It's not in a cluster but directly in the map, do something about it.
    marker.openPopup();
  }
}

1
我找到了解决这个问题的方法。在尝试在集群中打开弹出窗口之前,我会传送到该位置的坐标。然后集群将自动打开。
map.setView([coordinates[1], coordinates[0]], 20);

我定义应使用哪些坐标以及缩放级别。在此函数之后,我使用layer.openPopup()函数打开弹出窗口。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接