[GIS] Leaflet – get bounds of all layers, not just vector

leaflet

I need to get the bounds of all layers in a Leaflet map, not just vector layers. For vectors, I add them to a L.featureGroup, which has the method getBounds(). How do I include raster layers as well?

Best Answer

In the case of raster layers being L.imageOverlay's, you must have instantiated them specifying the image bounds.

If for any reason you lost reference of these bounds, you can retrieve them using myImageOverlay._bounds.

We could even imagine extending the L.ImageOverlay class to include a getBounds() method, so that it becomes compatible when embedded in a Feature Group with the latter own getBounds() method:

L.ImageOverlay.include({ // to be included in your script before instantiating image overlays.
    getBounds: function () {
        return this._bounds;
    }
});

var myImageOverlay = L.imageOverlay(imageUrl, bounds);

var myFeatureGroup = L.featureGroup([myImageOverlay]);

var myBounds = myFeatureGroup.getBounds();