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?

3
  • There are many tools that would let you do that: npmjs.com/package/geojson-bounds, and npmjs.com/package/geojson-bbox, and terraformer.io/glossary/#bbox for instance. Do you want to be able to do this in a specific programming language or using a GUI? Commented Feb 5, 2018 at 8: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
    Commented Feb 5, 2018 at 8:34
  • This information should go into the question body, please update the requirements Commented Feb 5, 2018 at 11:10

2 Answers 2

1

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
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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.