12

I have django app with leaflet on the frontend and I need to calculate the bbox of a geojson object so that I can pass the coordinates to map.fitBounds()

I have tried some libs as well as trying the getBounds methods of certain objects in Leaflet, such as FeatureGroup, but it complained that the bounds were not defined.

Can anyone point me to a simple solution to this?

  • 1
    In general, map.fitBounds(featureGroupName.getBounds()) should work, as long as the FeatureGroup contains data. Have you examined the FeatureGroup to see what it looks like at the time you are trying to get the bounds? – nathansnider Oct 18 '15 at 19:23
23

If you want to calculate the bounds of a GeoJSON-Layer you can do:

var geojsonLayer = L.geoJson(your_data).addTo(map);
map.fitBounds(geojsonLayer.getBounds());

Example: http://jsfiddle.net/expedio/qgkbrjwt/

(Map zooms to Layer extent after the Layer is completely loaded).

If you want to calculate the Bounds of each single feature you can do the following:

var myGeoJSON = L.geoJson(data, {
    onEachFeature: function (feature, layer) {
        // assign bounds to feature
        feature.properties.bounds_calculated = layer.getBounds();
    }
}).addTo(map);

// do whatever you want with
// feature.properties.bounds_calculated

Example: http://jsfiddle.net/expedio/fxxguv0v/

(Zoom to feature function in each popup)

2

Use geojson-bbox to calculate the bbox of any geojson

Usage:

<script src="path/to/geojson-bbox.min.js"></script>
var extent = bbox(geojson);
//extent is an array [left, bottom, right, top]

There is npm module for geojson-bbox

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.