0

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());
micha
  • 65
  • 11

1 Answers1

6

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.

tmcw
  • 11,536
  • 3
  • 36
  • 45
  • Thanks for your reply and your bind(this) hint. You helped me a lot. Had to do a little modification and now it's working: `var geojsonLayer = new L.GeoJSON.AJAX(url);` `geojsonLayer.on('data:loaded', function() {` `this.map.fitBounds(geojsonLayer.getBounds());` `geojsonLayer.addTo(this.map);` `}.bind(this));` – micha Apr 24 '15 at 13:14