The issue is that each Leaflet Marker Cluster Group (i.e. L.markerClusterGroup
) will perform its own clustering and render Clusters irrespective of what other Cluster Groups may display. Therefore if you have some individual Markers (or any point Features) that are in different Cluster Groups but close to each other, these Groups will display Clusters also close to each other, which may end up overlapping, especially at low zoom level, exactly like in your screenshot.
If you want your Markers to cluster all together (mixing "oranges with apples"), you should use a single Marker Cluster Group.
Now if I understand correctly, your "difficulty" is that you would like to be able to add and remove the Markers dynamically, i.e. in your case the user can use a Layers Control to switch on/off some Features on map.
In that case, you would probably be interested in Leaflet.FeatureGroup.SubGroup plugin (see demo). Simply create 1 subgroup per "switchable" Features Group and set their parent as your single Marker Cluster Group:
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/[email protected]/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
<!-- Leaflet.markercluster assets -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/MarkerCluster.Default.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.markercluster-src.js"></script>
<!-- Leaflet.FeatureGroup.SubGroup assets -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.featuregroup.subgroup.js"></script>
<div id="map"></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…