Extract Coordinates from KML BatchGeo File with Python

eamon1234 picture eamon1234 · Dec 4, 2012 · Viewed 9.9k times · Source

I've uploaded some addresses to BatchGeo and downloaded the resulting KML file from which I want to extract the coordinates. I managed to prettify the jumbled text file online here, but I don't know how to parse it to extract the co-ordinates.

<?xml version="1.0" ?>
<kml xmlns="http://earth.google.com/kml/2.0">
    <Document>
        <Placemark>
            <name>...</name>
            <description>....</description>
            <Point>
                <coordinates>-3.1034345755337,57.144817425039,0</coordinates>
            </Point><address>...</address>
            <styleUrl>#0</styleUrl>
        </Placemark>
    </Document>
</kml>

There seem to be several kml libraries for python but not much in the way of documentation (e.g. pyKML). Using the tutorial, I have got this far and created an 'lxml.etree._ElementTree' object but I'm not sure of its attributes:

from pykml import parser

kml_file = "BatchGeo.kml"

with open(kml_file) as f:

    doc = parser.parse(f)

coordinate = doc.Element("coordinates")
print coordinate

This gives the error:

AttributeError: 'lxml.etree._ElementTree' object has no attribute 'Element'

So how do I get a list of co-ordinates? Thanks.

Answer

eqzx picture eqzx · Dec 5, 2012
from pykml import parser

root = parser.fromstring(open('BatchGeo.kml', 'r').read())
print root.Document.Placemark.Point.coordinates

see the pykml docs

hope that helps!