Intersect a set polygons/multi-polygons at once and get the intersected polygon

299 Views Asked by At

I have a Geopandas data frame with five multi-polygons geometries. Now, I want to intersect all the geometries at once and get the intersected polygon out of it. I tried using unary union and polygonize but this is giving me a list of polygons but I want only one polygon that has the intersection of the set of multi-polygon polygons. How can we intersect a set of multi-polygon or polygons together and get the intersected polygon?

df=
location    geometry    
1          MULTIPOLYGON (((-0.304766 51.425882, -0.304904...    
2          MULTIPOLYGON (((-0.305968 51.427425, -0.30608 ...    
3          MULTIPOLYGON (((-0.358358 51.423471, -0.3581 5...    
4          MULTIPOLYGON (((-0.357654 51.413925, -0.357604...    
    rows=[]
    listpoly = [a.intersection(b) for a, b in combinations(df['geometry'], 2)]
    rings = []
    for poly in listpoly:
      if type(poly) == MultiPolygon:
         exterior_lines = LineString()
         for p in poly:
            exterior_lines = exterior_lines.union(p.exterior)
         rings.append(exterior_lines)
      elif type(poly) == Polygon:
         rings.append(LineString(list(poly.exterior.coords)))
    union = unary_union(rings)
    result = [geom for geom in polygonize(union)]
    print(result)
MULTILINESTRING((-0.0345 54.900...))
MULTILINESTRING((-0.045 54.200...))
MULTILINESTRING((-0.05 54.650...))
MULTILINESTRING((-0.04 54.750...))
1

There are 1 best solutions below

0
On BEST ANSWER

Shapely's intersect_all function can help you out.

Code sample:

import geopandas as gpd
from matplotlib import pyplot as plt
import shapely
import shapely.plotting

data = [
    {"geometry": shapely.box(0, 0, 100, 100), "color": "blue"},
    {"geometry": shapely.box(50, 50, 150, 150), "color": "green"},
    {"geometry": shapely.box(25, 75, 75, 125), "color": "yellow"},
]

data_gdf = gpd.GeoDataFrame(data)
result = shapely.intersection_all(data_gdf.geometry)
print(result)

data_gdf.plot(color=data_gdf["color"], alpha=0.50)
shapely.plotting.plot_polygon(result, color="red", linewidth=2)
plt.show()

Result is the red square:

enter image description here