Reading MultiGeometry KML file using Geopandas

2k Views Asked by At

I have a kml file with multi-geometries (points and polygons). I want to access only the polygons present inside the kml file.

I tried reading the kml file using Geopandas-

inputfile = 'path to kml file' fiona.supported_drivers['KML'] = 'rw' sp = gpd.read_file(inputfile, driver='KML')

here 'sp' variable only reads the point features present inside the kml file. I tried using 'Geometry' argument along with the driver argument, but still only the point features are read.

Can anyone help me in accessing the 'Polygon' entities in the kml file?

1

There are 1 best solutions below

2
Adam On

I had this same question today! I was obtaining the KML through a URL response however, so I was able to "remove" the point data prior to writing it as a kml file (now only with polygon data). This is what I did:

from bs4 import BeautifulSoup as bs
import geopandas as gpd
import fiona
fiona.drvsupport.supported_drivers['kml'] = 'rw'
fiona.drvsupport.supported_drivers['KML'] = 'rw'

soup = bs(r.content, 'xml')  # kml/xml content obtained from hitting an API
child = soup.find_all('Placemark')
child_polys = []

# Creates list of only polygon feature data
for c in child:
    if c.find('Point') == None:
        child_polys.append(c)

# Add required header/footer to the polygon data, then join below. 
header = ['''<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
  <open>
   1
  </open>''']

header.extend(child_polys)
header.append('''</Document>
</kml>''')

with open('temp_data.kml', 'w') as f:
    f.write(''.join([str(x) for x in header]))

data = gpd.read_file(r"temp_data.kml", driver="kml")

This got me a geodataframe with a column of names, description and geometry for the polygons only. In your case, you may have to find a way to read in the kml, then edit it as I did above, before reconstructing and passing to geopandas. Good luck.