答案 0 :(得分:4)
问题在于,每个 Leaflet Marker Cluster Group(即L.markerClusterGroup
)将执行其自身的聚类并呈现“聚类”,而与其他“聚类组”可能显示的无关。因此,如果您有一些单独的标记(或任何点要素)位于不同的群集组中但彼此接近,则这些组将显示彼此接近的群集,这可能最终会重叠,尤其是在低缩放级别时,就像在您的屏幕截图中。
如果您希望标记将所有聚集在一起(将“橘子和苹果混合”),则应使用单个标记聚集组。
现在,如果我理解正确,那么您的“难题”就是您希望能够动态添加和删除标记,即,在这种情况下,用户可以使用Layers Control来打开/关闭某些功能在地图上。
在这种情况下,您可能会对Leaflet.FeatureGroup.SubGroup插件感兴趣(请参阅demo)。只需为每个“可切换”功能组创建一个子组,并将其父级设置为您的单个标记群集组:
var map = L.map('map', {
maxZoom: 18,
}).setView([48.86, 2.35], 11);
var parentGroup = L.markerClusterGroup().addTo(map);
var overlays = {};
for (var i = 1; i <= 5; i += 1) {
overlays['Group ' + i] = L.featureGroup.subGroup(
parentGroup,
getArrayOfMarkers()
).addTo(map);
}
L.control.layers(null, overlays, {
collapsed: false,
}).addTo(map);
function getArrayOfMarkers() {
var result = [];
for (var i = 0; i < 10; i += 1) {
result.push(L.marker(getRandomLatLng()));
}
return result;
}
function getRandomLatLng() {
return [
48.8 + 0.1 * Math.random(),
2.25 + 0.2 * Math.random()
];
}
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
html,
body,
#map {
height: 100%;
margin: 0;
}
<!-- Leaflet assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
<!-- Leaflet.markercluster assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.3.0/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.3.0/dist/MarkerCluster.Default.css">
<script src="https://unpkg.com/leaflet.markercluster@1.3.0/dist/leaflet.markercluster-src.js"></script>
<!-- Leaflet.FeatureGroup.SubGroup assets -->
<script src="https://unpkg.com/leaflet.featuregroup.subgroup@1.0.2/dist/leaflet.featuregroup.subgroup.js"></script>
<div id="map"></div>
另请参阅Cluster multiple Layers with markercluster
注意:对于更复杂的用例,还有另一个插件Leaflet.MarkerCluster.LayerSupport。
另请参阅How to apply leaflet marker cluster using layers
披露:我是这些插件的作者。