1

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?

2

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());
    });
});
1

Almost there! You must wait for layeradd event for that. Just add an event handler and wrap your call inside

var polygonGroup = new L.FeatureGroup(); 
polygonGroup.on('layeradd', function(e){
    /* try console.log(e.layer) */
    map.fitBounds(polygonGroup.getBounds());
});
// Add group to map
map.addLayer(polygonGroup);

// then add your call
// Load kml and add to feature group
$.each(kmls, function (i, kmlUrl) {
    var polygonLayer = omnivore.kml(kmlUrl);
    polygonGroup.addLayer(polygonLayer);
});
  • This didn't really work either as polygonGroup seems to have no bounds when the 'layeradd' handler is called. Maybe its because im getting the kml list after an AJAX async request.. I managed to solve it though so I will include my answer, maybe it helps someone else :) – George Jan 14 '18 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.