1

I cannot get the fitBounds command to work on a project where I am bringing in data to a featureLayer using GeoJSON.

This:

map.fitBounds(pointsFeatureGroup.getBounds()); // Uncaught Error: Bounds are not valid. at e.fitBounds (leaflet.js:5)

and this:

var bounds = L.latLngBounds(pointsFeatureGroup); // Uncaught Error: Bounds are not valid. at e.fitBounds
map.fitBounds(bounds);

don't work

My simplified code is here: https://github.com/DPB61/leafletjs_problem2

If I just bring in markers individually into a normal Layer then a command like this works:

map.fitBounds(PointsLayer.getBounds());

but that raises other issues with other functionality for which a features layer is required.

Am I doing something wrong?

DB61
  • 23
  • 1
  • 5

1 Answers1

2

The root cause is a classic asynchronous issue.

See How do I return the response from an asynchronous call?

At the time you call map.fitBounds(vesselsFeatureGroup.getBounds()), the vesselsFeatureGroup is still empty (no child layer), therefore Leaflet cannot compute bounds.

Simply call the getBounds and fitBounds within the callback of your asynchronous task ($.getJSON)

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • Looks like I have a lot more study to do! Even after the 2nd read a lot of that went over my head. But I do see from your post what the cause of the problem is and study the info in the link to move further. – DB61 Jul 10 '17 at 04:49