Skip to content

Instantly share code, notes, and snippets.

@JamesChevalier
Created March 15, 2016 01:23
Show Gist options
  • Save JamesChevalier/b03b7423bf330f959076 to your computer and use it in GitHub Desktop.
Save JamesChevalier/b03b7423bf330f959076 to your computer and use it in GitHub Desktop.
Get the bounding box of a GeoJSON object, regardless of how many polygons it contains. The core of this is from http://mikefowler.me/2014/06/10/drawing-geojson-in-a-canvas/
function getBoundingBox(data) {
var bounds = {}, coordinates, point, latitude, longitude;
// Loop through each "feature"
for (var i = 0; i < data.features.length; i++) {
coordinates = data.features[i].geometry.coordinates;
if(coordinates.length === 1){
// It's only a single Polygon
// For each individual coordinate in this feature's coordinates...
for (var j = 0; j < coordinates[0].length; j++) {
longitude = coordinates[0][j][0];
latitude = coordinates[0][j][1];
// Update the bounds recursively by comparing the current xMin/xMax and yMin/yMax with the current coordinate
bounds.xMin = bounds.xMin < longitude ? bounds.xMin : longitude;
bounds.xMax = bounds.xMax > longitude ? bounds.xMax : longitude;
bounds.yMin = bounds.yMin < latitude ? bounds.yMin : latitude;
bounds.yMax = bounds.yMax > latitude ? bounds.yMax : latitude;
}
} else {
// It's a MultiPolygon
// Loop through each coordinate set
for (var j = 0; j < coordinates.length; j++) {
// For each individual coordinate in this coordinate set...
for (var k = 0; k < coordinates[j][0].length; k++) {
longitude = coordinates[j][0][k][0];
latitude = coordinates[j][0][k][1];
// Update the bounds recursively by comparing the current xMin/xMax and yMin/yMax with the current coordinate
bounds.xMin = bounds.xMin < longitude ? bounds.xMin : longitude;
bounds.xMax = bounds.xMax > longitude ? bounds.xMax : longitude;
bounds.yMin = bounds.yMin < latitude ? bounds.yMin : latitude;
bounds.yMax = bounds.yMax > latitude ? bounds.yMax : latitude;
}
}
}
}
// Returns an object that contains the bounds of this GeoJSON data.
// The keys describe a box formed by the northwest (xMin, yMin) and southeast (xMax, yMax) coordinates.
return bounds;
}
@vhermecz
Copy link

vhermecz commented Apr 30, 2021

Watch out, if you have a polygon with holes, the coordinates.length will be over 1. You should use the geometry.type field to determine if it is Polygon or MultiPolygon. E.g.: https://gist.github.com/andrewharvey/971b9db1900a62efa7635f6a6d337ae7#file-polygon-with-a-hole-geojson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment