-
-
Save goliatone/66ba0eda609258c97f183988f6641f6c 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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment