Leaflet markercluster:如何创建带有编号标记的markercluster?

Leaflet markercluster: How can I create a markercluster with numbered markers?

我正在尝试创建一个具有带 ID 标记的标记集群,因为稍后我想从地图中删除单个标记。但是,我什至无法让这些带标签的标记出现在地图上。我正在从 geoJSON 格式的变量 individualPoints 加载它们。我可以使用以下代码片段直接将这些标记添加到地图中:

// create object to save markers
var markersID = {};

// exchanges latitude & longitude
function switchLatLong(oldLocation) {
  return new L.LatLng(oldLocation[1], oldLocation[0]);
}

var geoJsonLayer = L.geoJson(individualPoints, {
  onEachFeature: function(feature, layer) {
    /* can add directly to the map--this works */
    markersID[feature.properties.id] = 
        L.marker(switchLatLong(feature.geometry.coordinates))
            .addTo(map);
  }
});

但我希望它们在一个集群中,所以我想我需要用一个 ID 标记每个标记(如 this question),然后将这个组添加到集群中,如下所示:

var geoJsonLayer = L.geoJson(individualPoints, {
  onEachFeature: function(feature, layer) {
    /* tag the marker with the id */
    markersID[feature.properties.id] = 
        L.marker(switchLatLong(feature.geometry.coordinates));
  }
});

// create a marker cluster group, and add the markers to this.
var markers = L.markerClusterGroup({});
/* here's where I'm trying to toggle to use the markers with ID numbers */
//markers.addLayer(geoJsonLayer); // this works
markers.addLayers(markersID);   // this doesn't

添加 geoJsonLayer 就可以了,但是添加 markersID 就不行了。所以我必须错误地添加 markersID 。 这是一个jsfiddle。 https://jsfiddle.net/anfw0n6w/

问题: 有没有更好的方法来创建具有 ID 的标记,我可以稍后参考?我还能如何将 markersID 添加到 markerClusterGroup?

Is there some better way to create markers that have an ID that I can refer to later?

有很多方法可以奏效:-)

How else can I add markersID to the markerClusterGroup?

因为你的 markersID 是一个普通对象,你不能。 addLayer 接受标记或图层组(如您的 L.geoJson),addLayers 接受标记的 数组

不要将稍后引用标记的需要与将标记添加到标记群集组的需要混为一谈。

发生的情况是,在您的 onEachFeature 中,您 复制了 您在 markersID 中的标记(创建新标记),而不是保留对由 L.geoJson 构建的相同 layer。如果你只保留对layer的引用,那么你可以直接引用那些标记,你可以直接将你的L.geoJson图层组添加到你的Marker Cluster Group:

var markersID = {};

var geoJsonLayer = L.geoJson(individualPoints, {
  onEachFeature: function(feature, layer) {
    // make a marker with that number
    // actually no need to duplicate the marker.
    //markersID[feature.properties.id] = L.marker(switchLatLong(feature.geometry.coordinates));
    markersID[feature.properties.id] = layer;
  }
});

markers.addLayer(geoJsonLayer); // this works
map.addLayer(markers);

// This will work, you just need to get the appropriate `id`.
markers.removeLayer(markersID[id]);

演示:https://jsfiddle.net/anfw0n6w/1/