【问题标题】:How to open popup for a specific marker inside a leaflet MarkerClusterGroup?如何在传单 MarkerClusterGroup 中打开特定标记的弹出窗口?
【发布时间】:2020-06-02 11:12:46
【问题描述】:

当地图缩小时,我想为标记簇下的标记打开一个弹出窗口。当用户点击搜索结果时调用此函数。

这是我正在使用的代码:

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
  • 当用户点击搜索结果时调用该函数。异步是早期版本的遗留物。我现在删除了它:)
  • ...您希望在缩小或获取搜索结果时打开弹出窗口吗?
  • 我希望在用户点击搜索结果时打开弹出窗口。当用户单击结果时,会找到位置 ID。使用此 ID,我想打开地图上某个位置的弹出窗口,包括集群中的位置。 :)

标签: javascript leaflet leaflet.markercluster


【解决方案1】:

因此,只要此类集群中的特定标记满足条件,您就想对集群的标记进行一些处理。

您可以遍历所有可见的集群标记,然后利用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();
  }
}

【讨论】:

    【解决方案2】:

    我找到了解决此问题的方法。在尝试打开集群中的弹出窗口之前,我会传送到该位置的坐标。然后集群会自动打开。

    map.setView([coordinates[1], coordinates[0]], 20);
    

    我定义了应该使用的坐标和缩放级别。在这个函数之后,我使用 layer.openPopup() 函数打开弹出窗口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多