In order to get the exterior coordinates I need to convert a shapely MultiPolygon to a Polygon. I do it like this:
if poly.geometry.type == 'Polygon':
x, y = poly.geometry.exterior.xy
elif poly.geometry.type == 'MultiPolygon':
allparts = [p.buffer(0) for p in poly.geometry]
poly.geometry = shapely.ops.cascaded_union(allparts)
x, y = poly.geometry.exterior.xy # here happens the error
This succeeds very often, but there are also cases where the Polygon obviously stays a MultiPolygon as the following error is still raised:
AttributeError: 'MultiPolygon' object has no attribute 'exterior'
I've checked, however, that every part of the MultiPolygon is a polygon and not itself a MultiPolygon:
>>>>[p.type for p in poly.geometry]
['Polygon', 'Polygon']
Any ideas why this happens and how to fix it?
Best Answer
You need to understand the Shapely binary predicates:
1) If the two polygons intersects the result of
union
orunary_union
(in red) is a Polygon therefore you can computes the exterior2) If the two polygons are disconnected, the result is necessary a MultiPolygon (in red with two polygons)
And if you work with Shapefiles, without topology, this may occur
A solution is to compute the Concave Hull but it is not really an union.