Skip to content

Commit 1782f31

Browse files
committed
tm geometries as bounding box, 7 digits #333
1 parent 3fb5b5e commit 1782f31

File tree

1 file changed

+68
-9
lines changed

1 file changed

+68
-9
lines changed

mapswipe_workers/mapswipe_workers/utils/geojson_functions.py

Lines changed: 68 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def csv_to_geojson(filename: str, geometry_field: str = "geom"):
2727
outfile,
2828
filename,
2929
"-sql",
30-
f'SELECT *, CAST({geometry_field} as geometry) FROM "{filename_without_path}"',
30+
f'SELECT *, CAST({geometry_field} as geometry) FROM "{filename_without_path}"', # noqa E501
3131
],
3232
check=True,
3333
)
@@ -101,28 +101,59 @@ def add_metadata_to_geojson(filename: str, geometry_field: str = "geom"):
101101
logger.info(f"added metadata to {filename}.")
102102

103103

104-
def create_group_geom(group_data):
104+
def create_group_geom(group_data, shape="bounding_box"):
105+
"""Create bounding box or convex hull of input task geometries."""
106+
105107
result_geom_collection = ogr.Geometry(ogr.wkbMultiPolygon)
106108
for result, data in group_data.items():
107109
result_geom = ogr.CreateGeometryFromWkt(data["wkt"])
108110
result_geom_collection.AddGeometry(result_geom)
109111

110-
group_geom = result_geom_collection.ConvexHull()
112+
if shape == "convex_hull":
113+
group_geom = result_geom_collection.ConvexHull()
114+
elif shape == "bounding_box":
115+
# Get Envelope
116+
lon_left, lon_right, lat_top, lat_bottom = result_geom_collection.GetEnvelope()
117+
118+
# Create Geometry
119+
ring = ogr.Geometry(ogr.wkbLinearRing)
120+
ring.AddPoint(lon_left, lat_top)
121+
ring.AddPoint(lon_right, lat_top)
122+
ring.AddPoint(lon_right, lat_bottom)
123+
ring.AddPoint(lon_left, lat_bottom)
124+
ring.AddPoint(lon_left, lat_top)
125+
group_geom = ogr.Geometry(ogr.wkbPolygon)
126+
group_geom.AddGeometry(ring)
127+
111128
return group_geom
112129

113130

114131
def create_geojson_file_from_dict(final_groups_dict, outfile):
115-
# TODO: adapt input name
132+
"""Take output from generate stats and create TM geometries.
133+
134+
In order to create a GeoJSON file with a coordinate precision of 7
135+
we take a small detour.
136+
First, we create a GeoJSONSeq file.
137+
This contains only the features.
138+
Then we add these features to the final GeoJSON file.
139+
The current shape of the output geometries is set to 'bounding_box'.
140+
"""
116141

117-
driver = ogr.GetDriverByName("GeoJSON")
142+
driver = ogr.GetDriverByName("GeoJSONSeq")
118143
# define spatial Reference
119144
srs = osr.SpatialReference()
120145
srs.ImportFromEPSG(4326)
146+
outfile_temp = outfile.replace(".geojson", "_temp.geojson")
147+
148+
if os.path.exists(outfile_temp):
149+
driver.DeleteDataSource(outfile_temp)
150+
121151
if os.path.exists(outfile):
122152
driver.DeleteDataSource(outfile)
123-
dataSource = driver.CreateDataSource(outfile)
153+
154+
dataSource = driver.CreateDataSource(outfile_temp)
124155
# create layer
125-
layer = dataSource.CreateLayer(outfile, srs, geom_type=ogr.wkbPolygon)
156+
layer = dataSource.CreateLayer(outfile_temp, srs, geom_type=ogr.wkbPolygon,)
126157

127158
# create fields
128159
field_id = ogr.FieldDefn("group_id", ogr.OFTInteger)
@@ -133,7 +164,8 @@ def create_geojson_file_from_dict(final_groups_dict, outfile):
133164
else:
134165
for group_id in final_groups_dict.keys():
135166
group_data = final_groups_dict[group_id]
136-
group_geom = create_group_geom(group_data)
167+
# create the final group geometry
168+
group_geom = create_group_geom(group_data, "bounding_box")
137169
final_groups_dict[group_id]["group_geom"] = group_geom
138170
# init feature
139171

@@ -163,8 +195,35 @@ def create_geojson_file_from_dict(final_groups_dict, outfile):
163195
print(group_geom)
164196
continue
165197

198+
# make sure to close layer and data source
166199
layer = None
167-
logger.info("created outfile: %s." % outfile)
200+
dataSource = None
201+
202+
# load the features from temp file
203+
feature_collection = []
204+
with open(outfile_temp, "r") as f:
205+
for cnt, line in enumerate(f):
206+
feature_collection.append(json.loads(line))
207+
208+
# create final geojson structure
209+
geojson_structure = {
210+
"type": "FeatureCollection",
211+
"name": outfile,
212+
"crs": {
213+
"type": "name",
214+
"properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"},
215+
},
216+
"features": feature_collection,
217+
}
218+
219+
# save to geojson
220+
with open(outfile, "w") as json_file:
221+
json.dump(geojson_structure, json_file)
222+
logger.info("created outfile: %s." % outfile)
223+
224+
# remove temp file
225+
if os.path.exists(outfile_temp):
226+
driver.DeleteDataSource(outfile_temp)
168227

169228

170229
def create_geojson_file(geometries, outfile):

0 commit comments

Comments
 (0)