Leaflet featureGroup with tracks fitbounds invalid

141 views Asked by At

Is there a better way???

I am adding several tracks to a map (using leaflet-gpx plugin) and want to fit the maps to the bounds of all the added tracks.

By using a featureGroup layer to contain the tracks it is possible to used the fitBounds() method using the feature group. However the featureGroup does not have a loaded event to trigger the fitBounds() and the map also doesn't seem to have a suitable trigger.

Calling fitBounds() directly on the map after it is rendered fails with 'invalid bounds' error. However delaying the call for about a second allows it to execute correctly.

I presume what is happening is that it takes time for all of the gpx layers in the group to be loaded and until that is complete the group can't return a valid set of bounds.

So using a setTimeout to delay the fitBounds() works, but causes some annoying flashing as the map re-renders itself. Is there a better way?

This works:

// mapname has been created and tracks have already been loaded into their individual layers    
    var tracksLayer = L.featureGroup([track1,track2,track3]);
    tracksLayer.addTo(mapname);

//this works, with more and complex tracks you might need a longer timeout
    setTimeout(function(){ mapname.fitBounds(tracksLayer.getBounds()); }, 1000);

// this however does not work
    // mapname.on('load', function() { mapname.fitBounds(tracksLayer.getBounds());});
//nor does this despite the fact that by this stage the map has been created and the featureGroup added
    // mapname.fitBounds(tracksLayer.getBounds());
0

There are 0 answers