Skip to content Skip to sidebar Skip to footer

Read Kml File With Multiple Placemarks In Pykml

In pykml, I can read the first placemark in a file using the following code: with open(filename) as f: pm = parser.parse(f).getroot().Document.Folder print 'got :'

Solution 1:

Edit: An even easier solution, assuming all placemarks are in one folder:

from pykml import parser

withopen(filename) as f:
  folder = parser.parse(f).getroot().Document.Folder

for pm in folder.Placemark:
  print(pm.name)

You can also use features of the underlying xml library lxml to search for placemark elements.

from pykml import parser
from pykml.factory import nsmap

namespace = {"ns": nsmap[None]}

withopen(filename) as f:
  root = parser.parse(f).getroot()
  pms = root.findall(".//ns:Placemark", namespaces=namespace)

  for pm in pms:
    print(pm.name)

If you specifically search for placemarks that have a Linestring child, you can also use xpath for more sophisticated searches.

pms = root.xpath(".//ns:Placemark[.//ns:LineString]", namespaces=namespace)

Solution 2:

This works:

withopen(filename) as f:
    doc = parser.parse(f).getroot().Document.Folder
for pm in doc.iterchildren():
    ifhasattr(pm, 'LineString'):
        print pm.LineString.coordinates

Post a Comment for "Read Kml File With Multiple Placemarks In Pykml"