Check if a polygon is a multipolygon in Shapely
Asked Answered
J

3

30

How can I check if a polygon entity is actually a multipolygon? I've tried:

if len(polygon) > 1:

but then get the error:

TypeError: object of type 'Polygon' has no len()

I've tried Nill, None and others, nothing worked.

Jankell answered 25/8, 2016 at 10:30 Comment(2)
You should check the manual. You can read about class MultiPolygon here: toblerity.org/shapely/manual.html#collections-of-polygonsLynn
This works only if your variable is a multipolygon. If it is not - you`ll get that error. This is why I want to check whether my variable is a polygon or a multipolygon.Jankell
P
58

Use the object.geom_type string (see general attributes and methods).

For example:

if poly.geom_type == 'MultiPolygon':
    # do multipolygon things.
elif poly.geom_type == 'Polygon':
    # do polygon things.
else:
    # raise IOError('Shape is not a polygon.')
Planetesimal answered 9/2, 2017 at 2:47 Comment(0)
J
7

Ok, this worked for me:

print ('type = ', type(poly))

outputs with:

type =  <class 'shapely.geometry.polygon.Polygon'>

in case of a polygon, and:

type =  <class 'shapely.geometry.multipolygon.MultiPolygon'>

in case of a multipolygon.

To check if a variable is a polygon or a multypolygon I did this:

if (isinstance(poly, shapely.geometry.multipolygon.MultiPolygon)):
    code...
Jankell answered 25/8, 2016 at 12:23 Comment(3)
Worth noting that this will not tell you how many rings the multipolygon has. A multipolygon may have only one exterior ring. That may not matter for your use case.Gerardgerardo
Using your isinstance() code, I get: NameError: name 'shapely' is not definedEmbow
@Embow that means you have not imported shapely (or not as shapely). Add import shapely to the top of your codeAsta
M
0

you can do this simply.

import shapely.geometry.multipolygon as sh

if isinstance(polygon, sh.MultiPolygon):
    print('yes I am')
Morehouse answered 30/6, 2021 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.