importgeopandasasgpdfromshapely.wktimportloadsimportxml.etree.ElementTreeasETimportosimportpandasaspdfromshapely.geometryimportLineString# Example usage
kml_dir='.'gdf_list=[]# Loop through all the KML files in the directory
forfilenameinos.listdir(kml_dir):iffilename.endswith('.kml')and'LINE'infilename:gdf=read_kml_to_gdf(filename)iflen(gdf)==0:continueroot=filename.replace('kml','')gdf.to_csv(root+'csv',index=False)forcingdf.columns:ifc!='geometry':delgdf[c]gdf_list.append(gdf)iflen(gdf_list)==0:sys.exit('fail')all_gdf=pd.concat(gdf_list,ignore_index=True)all_gdf.to_csv('line3D.csv',index=False)
defread_kml_to_gdf(kml_file):tree=ET.parse(kml_file)root=tree.getroot()ns={'kml':'http://www.opengis.net/kml/2.2'}features=[]forplacemarkinroot.findall('.//kml:Placemark',ns):name=placemark.find('kml:name',ns).textgeom_type=placemark.find('kml:LineString',ns)isnotNoneifgeom_type:coordinates=placemark.find('kml:LineString/kml:coordinates',ns).text.strip()coords=[tuple(map(float,coord.split(',')))forcoordincoordinates.split()]geometry=LineString(coords)# Extract the extended data
extended_data=placemark.find('kml:ExtendedData',ns)ifextended_dataisnotNone:schema_data=extended_data.find('kml:SchemaData',ns)ifschema_dataisnotNone:attributes={elem.attrib['name']:elem.textforeleminschema_data.findall('kml:SimpleData',ns)}else:attributes={}feature={'name':name,'geometry':geometry,**attributes}features.append(feature)else:# Handle other geometry types if needed
continuegdf=gpd.GeoDataFrame(features,geometry='geometry')returngdf