3

I have a geojson file containing a FeatureCollection, where each feature contains a geometry of type "Polygon". I would like to replace the polygons to rectangular bounding boxes in a simple batch manner. That being said, I could also live with the geometry remaining of type "Polygon", but then of course with just four nodes consisting of the min and max lat/lon coordinates of the former multi-node polygon.

Is there any simple way to do it, favorably some existing algorithm or web service?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Michael
  • 1,186
  • 13
  • 29
  • There are many tools that would let you do that: https://www.npmjs.com/package/geojson-bounds, and https://www.npmjs.com/package/geojson-bbox, and http://terraformer.io/glossary/#bbox for instance. Do you want to be able to do this in a specific programming language or using a GUI? – Alex Tereshenkov Feb 05 '18 at 08:15
  • I don't particularly care as long as it works under Ubuntu/Python and uses open source software. The problem of the tools you proposed seems to be that they work on one feature at a time. I don't know if they were able to loop over a whole Feature Collection. – Michael Feb 05 '18 at 08:34
  • This information should go into the question body, please update the requirements – Alex Tereshenkov Feb 05 '18 at 11:10

2 Answers2

1

Thanks to a colleague, I found the solution with a simple Python script:

from osgeo import ogr
import json;
filename="yourOriginalFile.geojson"
with open (filename, "r") as myfile:
    data=myfile.read()

dataset = json.loads(data)

for f in dataset["features"]:
    c = f["geometry"]["coordinates"][0]
    c1 = [x[0] for x in c] # first coordinate
    c2 = [x[1] for x in c]
    bbox = [[min(c1),min(c2)],[min(c1),max(c2)],[max(c1),max(c2)],[max(c1),min(c2)],[min(c1),min(c2)]]
    f["geometry"]["coordinates"] = [bbox]

with open("yourOutputFile.geojson","w") as f:
    json.dump(dataset,f)

This basically replaces the old multi-node polygons by closed polygons consisting of just four corners.

Michael
  • 1,186
  • 13
  • 29
  • 3
    It looks still unnecessary complicated because there is a ready made GetEnvelope. See usage example https://gis.stackexchange.com/questions/90205/equivalent-function-to-shapelys-envelope-in-ogr – user30184 Feb 05 '18 at 13:24
0

For example with GDAL and SQLite/SpatiaLite dialect.

Test with ogrinfo

ogrinfo -dialect sqlite -sql "select ST_Envelope(geometry) from test limit 2"  test.json

Save into new file with ogr2ogr

ogr2ogr -f GeoJSON -dialect sqlite -sql "select ST_Envelope(geometry) AS geometry, attribute_1, attribute_2 from test" output.json input.json
user30184
  • 65,331
  • 4
  • 65
  • 118