JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.1.0/dist/leaflet-src.js"></script>
<script src="https://unpkg.com/leaflet.featuregroup.subgroup@1.0.2/dist/leaflet.featuregroup.subgroup-src.js"></script>
<div id="map"></div>
CSS
#map {
height: 500px;
}
JavaScript
var map = L.map("map");
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map);
map.setView([48.85, 2.35], 12);
var parentGroup = L.featureGroup().addTo(map),
subGroup1 = L.featureGroup.subGroup(parentGroup),
subGroup2 = L.featureGroup.subGroup(parentGroup);
for (var i = 0; i < 10; i += 1) {
L.marker(getRandomLatLng()).addTo(subGroup1);
}
for (i = 0; i < 10; i += 1) {
L.marker(getRandomLatLng2()).addTo(subGroup2);
}
var overlays = {
'SubGroup 1': subGroup1,
'SubGroup 2': subGroup2
};
L.control.layers(null, overlays, {
collapsed: false
}).addTo(map);
map.on('overlayadd overlayremove', function () {
var bounds = parentGroup.getBounds();
// Fit bounds only if the Parent Group actually has some markers,
// i.e. it returns valid bounds.
if (bounds.isValid()) {
map.fitBounds(bounds);
}
});
function getRandomLatLng() {
return [
48.8 + 0.05 * Math.random(),
2.25 + 0.1 * Math.random()
];
}
function getRandomLatLng2() {
return [
48.85 + 0.05 * Math.random(),
2.35 + 0.1 * Math.random()
];
}