Reputation: 51
Im trying to create a features array using python and python-geojson. I appended some features such as Polygon with working coordinates. However when I dump, there is no indentation in the geoJson file. It is all on one line and mapbox does not accept the data.
f
features = []
poly = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
features.append(Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]]))
features.append(Feature(geometry=poly, properties={"country": "Spain"}))
feature_collection = FeatureCollection(features)
with open('myfile.geojson', 'w') as f:
dump(feature_collection,f)
f.close()
Thats how the output looks. It should be indented instead of clustered like that.
{"type": "FeatureCollection", "features": [{"type": "Polygon", "coordinates": [[[2.38, 57.322], [23.194, -20.28], [-120.43, 19.15], [2.38, 57.322]]]}, {"geometry": {"type": "Polygon", "coordinates": [[[2.38, 57.322], [23.194, -20.28], [-120.43, 19.15], [2.38, 57.322]]]}, "type": "Feature", "properties": {"country": "Spain"}}]}
Upvotes: 2
Views: 3696
Reputation: 807
Backing up a bit, there are three types of GeoJSON objects:
A Feature
includes a Geometry
, and a FeatureCollection
includes one or more Features
. You can't directly put a Geometry
inside a FeatureCollection
, however, it needs to be a Feature
.
In the example you've shared, your FeatureCollection
includes one Feature
and one Geometry
(in this case, a Polygon
). You'll need to convert that Polygon
to a Feature
before adding it to a FeatureCollection
.
Not sure if you intended to have two identical polygons, but your example would need to look something like this to output valid GeoJSON:
features = []
poly1 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
poly2 = Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
features.append(Feature(geometry=poly1, properties={"country": "Spain"}))
features.append(Feature(geometry=poly2))
feature_collection = FeatureCollection(features)
with open('myfile.geojson', 'w') as f:
dump(feature_collection,f)
f.close()
Indentation shouldn't matter here.
You can read more than you ever wanted to know about the GeoJSON spec at https://www.rfc-editor.org/rfc/rfc7946.
Upvotes: 0
Reputation: 23139
Add an 'indent' param to your dump() call:
with open('myfile.geojson', 'w') as f:
dump(feature_collection, f, indent=4)
It's strange, however, that a piece of code won't accept JSON that is all on one line. It's just as much valid, legal JSON. That's a bug in that code. Using the 'indent' param is usually done just for human readability.
Upvotes: 1