micha
micha

Reputation: 65

Leaflet AJAX Map FitBounds

I am searching for a solution to fit a leaflet map's bounds to display the content of a loaded geoJSON file.

For loading the file I use leaflet-ajax. I tried already this, but I have no idea how I can get the layer's bounds. Any Suggestions how I can adjust the displayed map sector to display the geoJSON file? Thanks.

var geojsonLayer = new L.GeoJSON.AJAX('http://localhost:8080/test.geojson');
geojsonLayer.addTo(this.map);
this.map.fitBounds(geojsonLayer.getBounds());

Upvotes: 0

Views: 1464

Answers (1)

tmcw
tmcw

Reputation: 11882

AJAX means asynchronous: so the fitBounds call will run before the content is loaded. To do this correctly, you'd wait for the data:loaded event.

var geojsonLayer = new L.GeoJSON.AJAX('http://localhost:8080/test.geojson');
geojsonLayer.addTo(this.map);
geojsonLayer.on('data:loaded', function() {
  this.map.fitBounds(geojsonLayer.getBounds());
}.bind(this));

With the .bind(this) because the callback will have a different this value by default.

Upvotes: 6

Related Questions