J.Doe
J.Doe

Reputation: 181

Google KML file to python

I have the following code to access coordinates of kml files in python

from pykml import parser
with open('test.kml', 'r') as kml_file:
root = parser.parse(kml_file).getroot()
for i in root.findall('{http://www.opengis.net/kml/2.2}Document/{http://www.opengis.net/kml/2.2}Placemark/{http://www.opengis.net/kml/2.2}Point'):
print(i.coordinates)

This one finds me all individual points in the kml file, where I marked a certain points of interest. But I also have some polygons of points that I created in google earth and this algorithm does not return them. How can I also get the polygons?

Please let me know if you have any questions.

Upvotes: 1

Views: 11516

Answers (1)

CodeMonkey
CodeMonkey

Reputation: 23778

If the KML source file has a Document with Placemarks then the following Python code will iterate over each Placemark with a Polygon geometry and dump out the coordinates.

from pykml import parser
with open('test.kml', 'r') as f:
  root = parser.parse(f).getroot()
namespace = {"kml": 'http://www.opengis.net/kml/2.2'}
pms = root.xpath(".//kml:Placemark[.//kml:Polygon]", namespaces=namespace)
for p in pms:
  print(p.Polygon.outerBoundaryIs.LinearRing.coordinates)

If the KML uses MultiGeometry with one or more Polygons then a small change is needed to the check inside the for loop.

for p in pms:
  if hasattr(p, 'MultiGeometry'):
    for poly in p.MultiGeometry.Polygon:
      print(poly.outerBoundaryIs.LinearRing.coordinates)
  else:
    print(p.Polygon.outerBoundaryIs.LinearRing.coordinates)

Without using XPATH.

You can also just interact over a KML document structure and recursively iterate over children in Document and Folder elements.

import re
from pykml import parser

def parse(root):
    for elt in root.getchildren():
        # strip the namespace
        tag = re.sub(r'^.*\}', '', elt.tag)
        if tag in ["Document", "Folder"]:
            # recursively iterate over child elements
            parse(elt)
        elif tag == "Placemark":
            if hasattr(elt, 'Point'):
                print("Point:", elt.Point.coordinates)
            elif hasattr(elt, 'LineString'):
                print("LineString:", elt.LineString.coordinates)
            elif hasattr(elt, 'Polygon'):
                print("Polygon:", elt.Polygon.outerBoundaryIs.LinearRing.coordinates)
            elif hasattr(elt, 'MultiGeometry'):
                print("MultiGeometry")
                for gg in elt.MultiGeometry.getchildren():
                    tag = re.sub(r'^.*\}', '', gg.tag)
                    if tag == "Polygon":
                        print(gg.outerBoundaryIs.LinearRing.coordinates)

with open('test.kml', 'r') as f:
    root = parser.parse(f).getroot()
parse(root)

Upvotes: 3

Related Questions