Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Leaflet featureGroup with tracks fitbounds invalid

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());
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!