From 853304fae2c0af6ad059a2d77b8a09784d2a9999 Mon Sep 17 00:00:00 2001 From: Sujan Adhikari <109404840+Sujanadh@users.noreply.github.com> Date: Fri, 5 Apr 2024 13:56:57 +0545 Subject: [PATCH] refactor: merged multi polygon to single polygon (#1426) Co-authored-by: sujanadh --- src/backend/app/projects/project_crud.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/backend/app/projects/project_crud.py b/src/backend/app/projects/project_crud.py index 8d988794ed..234b94dc93 100644 --- a/src/backend/app/projects/project_crud.py +++ b/src/backend/app/projects/project_crud.py @@ -46,10 +46,8 @@ from osm_fieldwork.xlsforms.entities import registration_form from osm_rawdata.postgres import PostgresClient from shapely import wkt -from shapely.geometry import ( - Polygon, - shape, -) +from shapely.geometry import MultiPolygon, Polygon, mapping, shape +from shapely.ops import unary_union from sqlalchemy import and_, column, func, inspect, select, table, text from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session @@ -393,12 +391,19 @@ def remove_z_dimension(coord): # Merge multiple geometries into single polygon if multi_polygons: - geometry = multi_polygons[0] - for geom in multi_polygons[1:]: - geometry = geometry.union(geom) - for feature in features: - feature["geometry"] = geometry + merged_polygon = unary_union(multi_polygons) + if isinstance(merged_polygon, MultiPolygon): + merged_polygon = merged_polygon.convex_hull + merged_geojson = mapping(merged_polygon) + features = [ + { + "type": "Feature", + "properties": {}, + "geometry": merged_geojson, + } + ] boundary["features"] = features + return await run_in_threadpool( lambda: split_by_square( boundary,