Atihska
Atihska

Reputation: 5126

How can I convert list of polygons in wkt form to a multipolygon?

I have a list of polygons where each polygon is a wkt form as follows:

list_polygons =  ['POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))', 
                  'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))']

I want to convert into a multi polygon wkt as:

'MULTIPOLYGON (((-88.131229288 41.900200029, -88.12973798 41.900104202, -88.12978599900001 41.894907769, -88.131352409 41.895051521, -88.131229288 41.900200029)), ((-88.121359263 41.887694051, -88.12027565 41.887654116, -88.120264921 41.884451192, -88.11968556399999 41.884483142, -88.11962119099999 41.882669946, -88.121251974 41.882637995, -88.121359263 41.887694051)))'

I tried the following but gives me AssertionError:

from shapely.geometry.multipolygon import MultiPolygon
Multipolygon(list_polygons)

I also tried to debug like this

p = wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200
029))')
*** SyntaxError: SyntaxError('invalid syntax', ('<string>', 1, 1, "= wkt.loads('POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))')"))

What is it that I am doing wrong?

Upvotes: 0

Views: 5185

Answers (1)

Grismar
Grismar

Reputation: 31329

Your list_polygons is actually a list of strings, you need to turn them into polygons and then use the MultiPolygon constructor to create what you need:

import shapely.wkt as wkt
from shapely.geometry import MultiPolygon

list_string = [
    'POLYGON ((-88.131229288 41.900200029,-88.12973798 41.900104202,-88.129785999 41.894907769,-88.131352409 41.895051521,-88.131229288 41.900200029))',
    'POLYGON ((-88.121359263 41.887694051,-88.12027565 41.887654116,-88.120264921 41.884451192,-88.11968556399999 41.884483142,-88.11962119099999 41.882669946,-88.121251974 41.882637995,-88.121359263 41.887694051))'
]

c = MultiPolygon(map(wkt.loads, list_string))

print(c)

This example uses map, but you can apply the wkt.loads() function any way you like, of course.

What the line actually does: applies the wkt.loads() function to every element of the list_string list, passing the resulting iterator to the MultiPolygon constructor, which expects it to represent a collection of polygons that should represent the outsides of your shapes (not holes, that would be a second collection).

Upvotes: 2

Related Questions