How can I get of the extent of all features within a GeoJSON FeatureCollection with Python 3? One extent for all features, not one per feature.
The Feature collection includes multiple points features and multiple LineStrings features.
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
Here's the way I do this, it doesn't require using ogr or shapely or anything outside of the core json library. This script is set up to crawl geojson with mixed geometries (point, linestring, polygon) but will work on single feature types too. It abstracts all coordinate pairs from their features, sticks them in a list, and then uses python's built-in
range() functions to identify the min/max.
You can always subtract/add some arbitrary float to the min/max (respectively) if you want some 'padding' around the lower left/upper right coordinates.
import json geojson_file = "path/to/file.json" with open(geojson_file, 'r') as geojson: xcoords =  ycoords =  data = json.load(geojson) for f in data['features']: geom = f['geometry'] for coord in geom['coordinates']: if type(coord) == float: # then its a point feature xcoords.append(geom['coordinates']) ycoords.append(geom['coordinates']) elif type(coord) == list: for c in coord: if type(c) == float: # then its a linestring feature xcoords.append(coord) ycoords.append(coord) elif type(c) == list: # then its a polygon feature xcoords.append(c) ycoords.append(c)
Then, assuming you want to make a new poly object, you can just ask the list for the min/max and line it up however you want. I use the following format cause I work mainly with arcpy:
extent = [ [min(ycoords), min(xcoords)], [max(ycoords), min(xcoords)], [max(ycoords), max(xcoords)], [min(ycoords), max(xcoords)] ]
I found the answer here with @Stefan_Fairphone's help...
The answer is here