Create button to center map with all the active layers

Viewed 74

I have a map with different layers. The user can choose between them with a L.control.layers. Is it possible to add a button that would center the map with all the active layers?

Thanks for any tips,

1 Answers

You can add all your layers to a FeatureGroup and then get the bounds. With that bounds you can center the map with map.fitBounds(bounds):

var fg = L.featureGroup().addTo(map);

layer1.addTo(fg);
layer2.addTo(fg);
....

function centerMap(){
   map.fitBounds(fg.getBounds());
}

As button you can use a default html button:

<button onclick="centerMap()">Center Map</button>
Related