Input data you have is probably a string(?) and it is almost in WKT (Well-known Text) format. Therefore, shapely.wkt.loads
method helps you. But first, you have to have closed coordinates. That's, the first (lat, long) must also be at the end of the string like:
vvvvvvv vvvvvvv
'POLYGON ((1.0 2.0, 10.0 20.0, 20.0 20.0, 1.0 2.0))'
The code:
import re
import numpy as np
from shapely import wkt
def add_closing_coordinates(d):
""" Adds the first 'lat long' to the end"""
i = re.search(r"\d", d).start()
j = re.search(r'(\d)[^\d]*$', d).start() + 1
c = d.index(',')
return d[:j] + ", " + d[i:c] + d[j:]
data = 'POLYGON ((1.0 2.0, 10.0 20.0, 20.0 20.0))'
data_wkt = add_closing_coordinates(data)
print(f"data_wkt: {data_wkt}")
# OUT: vvvvvvv
# data_wkt: POLYGON ((1.0 2.0, 10.0 20.0, 20.0 20.0, 1.0 2.0))
polygon = wkt.loads(data_wkt)
coords = np.dstack(polygon.boundary.xy).tolist()[0][:-1]
print(f"coords: {coords}")
# OUT:
# coords: [[1.0, 2.0], [10.0, 20.0], [20.0, 20.0]]
expected_list_of_coordinates_for_received_code = [{"lat": x, "lng": y} for x, y in coords]
print(expected_list_of_coordinates_for_received_code )
# OUT:
# [{'lat': 1.0, 'lng': 2.0},
# {'lat': 10.0, 'lng': 20.0},
# {'lat': 20.0, 'lng': 20.0}]