To fit to the visible markers only, I've this method.
fitMapBounds() {
// Get all visible Markers
const visibleMarkers = [];
this.map.eachLayer(function (layer) {
if (layer instanceof L.Marker) {
visibleMarkers.push(layer);
}
});
// Ensure there's at least one visible Marker
if (visibleMarkers.length > 0) {
// Create bounds from first Marker then extend it with the rest
const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
visibleMarkers.forEach((marker) => {
markersBounds.extend(marker.getLatLng());
});
// Fit the map with the visible markers bounds
this.map.flyToBounds(markersBounds, {
padding: L.point(36, 36), animate: true,
});
}
}