[GIS] Leaflet-omnivore load multiple KMLs & center

kmlleafletpolygon

I'm new with leaflet-omnivore and looking for the optimal way to load a number of KMLs (each of them containing a polygon) and center the map in their "bounds"

I have tried adding the loaded polygons to a feature group and then try to get the bounds of that in order to center the map. The polygons are showing on the map successfully but the map does not zoom/center

    var polygonGroup = new L.FeatureGroup();            

    // Load kml and add to feature group
    $.each(kmls, function (i, kmlUrl) {
        var polygonLayer = omnivore.kml(kmlUrl);
        polygonGroup.addLayer(polygonLayer);
    });

    // Add group to map
    map.addLayer(polygonGroup);

    // Attempt to center map
    map.fitBounds(polygonGroup.getBounds());`

Can anyone point me to the right direction?

Best Answer

I finally managed to solve it by getting the bounds and centering at the time of adding the kml to the FeatureGroup

var polygonGroup = new L.FeatureGroup();

// Add group to map
map.addLayer(polygonGroup);

$.each(kmls, function (i, kmlUrl) {
// Load kml and add to feature group
var runLayer = omnivore.kml(kmlUrl).addTo(polygonGroup).on('ready',
    function() {
        // Get group bounds and center/zoom
        map.fitBounds(polygonGroup.getBounds());
    });
});