javascriptajaxleafletfitbounds

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());


Solution

  • 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.