Python WKT to KML – How to Convert Polygons

convertkmlpythonwell-known-text

I have a set of data id with polygons.
I want to convert the dataframe to kml file using python.
an example of the data is like so

rtid_key,geometry 
40314,POLYGON ((106.79137124474583 -6.164311707677381, 106.79137168485848 -6.16430071122585, 106.79137307520114 -6.16426596840807, 106.79137669615109 -6.164175503602752, 106.79137834323835 -6.164134349202208, 106.79138197275725 -6.1640308206050936, 106.79144969286747 -6.164032648215645, 106.79160213326787 -6.1640326304020565, 106.7916574729182 -6.164032623404948, 106.79171577040032 -6.164032616404823, 106.7917598379467 -6.164032612027056, 106.79175983277797 -6.163986925050508, 106.79187559206979 -6.163980187552802, 106.79197024139476 -6.163974679275572, 106.79198748542723 -6.163973676417985, 106.79207757691844 -6.163968432099229, 106.79209639441683 -6.163967337145296, 106.792179616653 -6.163962492954774, 106.79221129829457 -6.163960648566995, 106.79227404736785 -6.163956997114851, 106.79230780468794 -6.163955032717686, 106.79238696678276 -6.163950424580226, 106.7924023753964 -6.163949528247264, 106.79247742587496 -6.1639451599717905, 106.79250389483283 -6.163943619726531, 106.79252305241418 -6.163941836428923, 106.7925857507736 -6.163936000585846, 106.79264003810863 -6.16393094712088, 106.79268430862815 -6.163926827012279, 106.79277631593811 -6.163918262275172, 106.79279571736541 -6.16391645644745, 106.79281698261964 -6.163914396601332, 106.79283631257286 -6.164204182693336, 106.79292392545213 -6.164197985405297, 106.79308273432663 -6.164186749133235, 106.79328953556394 -6.164172118853521, 106.79336420643305 -6.164164476744211, 106.79340623673474 -6.164160175133798, 106.79340899142281 -6.164451999776032, 106.79306733742756 -6.164466566661924, 106.79289300016804 -6.164473999722819, 106.7928463535784 -6.164480000434269, 106.7919543625494 -6.164594751249555, 106.79172700003795 -6.1646240004473105, 106.79172736933722 -6.16431062176255, 106.79137124474583 -6.164311707677381))

I am stuck at

import simplekml
from google.colab import files
import csv

kml=simplekml.Kml()
df = csv.reader(open('gp.csv','r'))
for row in df:
  kml.newpoint(name=row[0], coords=[(row[1])])
kml.save('kmlfile.kml')

However the polygon are not read properly, is there a formating that must be done? Because I tried loading the KML file and it does not load as it must in google my map.

Best Answer

Try this, using some modern packages.

import fiona
import pandas as pd
import geopandas as gpd 
from shapely import wkt

# Enable KML support
fiona.supported_drivers['KML'] = 'rw'

df = pd.read_csv('./gp.csv')

# convert wkt to geometries
geoms = [wkt.loads(shape_text) for shape_text in df.geometry.tolist()]

gdf = gpd.GeoDataFrame(df[['rtid_key']], geometry = gpd.GeoSeries(geoms, crs='EPSG:4326'))

gdf.to_file('kmlfile.kml', driver='KML')
Related Question