Python Shapely – How to Convert Polygon to List of Coordinates Using Shapely

coordinatesgeopandaspolygonpythonshapely

I received a code, that expects a list of coordinates such as this as input

area_polygon = [{'lat': 46.037286, 'lng': 14.471329},
                {'lat': 46.036733, 'lng': 14.467378},
                {'lat': 46.034822, 'lng': 14.468441}]

However, I have input data in form of shapely.Polygon and it looks like this:

POLYGON ((14.471329 46.037286, 14.467378 46.036733, 14.468441 46.034822))

I work with shapely and GeoPandas libraries and I know how to switch lats and longs. But I don't know how to do everything else to transform a Polygon to the form presented.

Best Answer

Here is another solution using the mapping():

returns a new, independent geometry with coordinates copied from the context.

import json
from shapely.geometry import Polygon, mapping

poly = Polygon([[14.471329,46.037286],[14.467378,46.036733],[14.468441,46.034822]])

poly_mapped = mapping(poly)

poly_coordinates = poly_mapped['coordinates'][0]

poly_ = [{'lat': coords[1],'lon': coords[0]} for coords in poly_coordinates]

print(json.dumps(poly_))

This results in:

[{"lat": 46.037286, "lon": 14.471329}, {"lat": 46.036733, "lon": 14.467378}, {"lat": 46.034822, "lon": 14.468441}, {"lat": 46.037286, "lon": 14.471329}]

Mind that the above output will contain one point two times, the first and last points, to avoid that use the following piece of code:

poly_ = poly_[:-1]

print(json.dumps(poly_))

This results in:

[{"lat": 46.037286, "lon": 14.471329}, {"lat": 46.036733, "lon": 14.467378}, {"lat": 46.034822, "lon": 14.468441}]

References: