I am now using the Leaflet.FeatureGroup.SubGroup plugin with the Leaflet.markercluster plugin. Trying to set map bound to all visible markers and marker clusters. I am using 3 co-ordinates to test:
[43.6425657, -79.38705569999999]
[43.7164673, -79.3395846]
[-41.3142772, 174.8135975]
This is the code so far:
var map = L.map("mapid");
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);
map.setView([43.6532, -79.3832], 2);
var parentGroup = L.markerClusterGroup().addTo(map),
consultingMarkers = L.featureGroup.subGroup(parentGroup).addTo(map),
otherMarkers = L.featureGroup.subGroup(parentGroup).addTo(map);
// subGroup1
L.marker([43.6425657, -79.38705569999999]).addTo(consultingMarkers);
L.marker([43.7164673, -79.3395846]).addTo(consultingMarkers);
// subGroup2
L.marker([-41.3142772, 174.8135975], {icon: otherIcon}).addTo(otherMarkers);
var overlays = {
'consulting': consultingMarkers,
'other': otherMarkers
};
L.control.layers(null, overlays, {
collapsed: false
}).addTo(map);
map.on('overlayadd overlayremove', function () {
var bounds = parentGroup.getBounds(),
southWest = bounds.getSouthWest();
// Fit bounds only if the Parent Group actually has some markers,
// i.e. it returns valid bounds.
if (southWest && !southWest.equals(bounds.getNorthEast())) {
map.fitBounds(parentGroup.getBounds());
}
});
So far, I am running into these problems:
Map does not bound to the [-41.3142772, 174.8135975] co-ordinate
Un-checking the "consulting" layer does not bound the map to the markers from the "other" layer which has the co-ordinate [-41.3142772, 174.8135975].
Update: it seems to have this bounding problem for single markers. I tried adding another marker co-ordinate [43.76089289999999, -79.4103427] which would be in the cluster. But if I remove "consulting" cluster and remove "other" layer. The map still does not bound to the last marker left on the map.
解决方案
If I understand correctly, you are puzzled because when one of your SubGroups has only 1 marker, the map.fitBounds does not look to be executed?
In that case, that is simply the expected behaviour of the !southWest.equals(bounds.getNorthEast()) check: it avoids executing the next block when bounds represents a null area, i.e. there is 0 or 1 marker into it.
By replacing the check by bounds.isValid(), you avoid only the case when there is 0 marker, but in the case there is exactly 1 marker, it will allow executing the next block, therefore trying to fit bounds on a null area. In such case, Leaflet pans to that single marker and zooms to maxZoom.
map.on('overlayadd overlayremove', function () {
var bounds = parentGroup.getBounds();
if (bounds.isValid()) {
map.fitBounds(bounds);
}
});