17

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
fccoelho
  • 1,237
  • 5
  • 13
  • 22
  • 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

2 Answers2

29

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)

Brian Burns
  • 768
  • 5
  • 13
Thomas B
  • 8,807
  • 1
  • 21
  • 62
5

Use the geojson-bbox module to calculate the bbox of any GeoJSON.

Download this geojson-bbox/dist /geojson-bbox.min.js file and save it in your project.

Usage:

.html file

</body>
    <script type="text/javascript" src="path/to/geojson-bbox.min.js"></script>
<body>

.js file:

// reading and parsing the GeoJSON file
const geojson = JSON.parse(geojsonfile);
// getting the bbox extent as an array [left, bottom, right, top] from the GeoJSON file
var gj_extent = bbox(geojson);

There is npm module for geojson-bbox

Node.js usage:

// const bbox = require('geojson-bbox'); // with CommonJS
import * as bbox from 'geojsjon-bbox';
const feature = { 
  type: 'Feature',
  geometry: {
    type: 'LineString', 
    coordinates: [
      [10, 40], [40, 30], [20, 20], [30, 10]
    ]
  }
};
const extent = bbox(feature); 
// extent is array 
// [10, 10, 40, 40]
Taras
  • 32,823
  • 4
  • 66
  • 137
Gagan
  • 201
  • 2
  • 5