[GIS] Converting kml to wkt using geodjango or python

convertgeodjangopython

in geodjango i found that i can use WKT to insert geometry such as:

pnt = GEOSGeometry('POINT(5 23)')

but it doesn't show how to do it if the data is KML, as my data is in kml format, so my plan is to convert KML -> WKT -> GEOSGeometry.

Is there a way to convert kml to wkt using geodjango or using any python library?

Best Answer

Here is a working solution, that assumes you have your KML data in a string. If its in a file, you can skip the first step where a temp file is created. The KML driver from ogr only reads from file as far as I know.

Tthere might be some more elegant ways of converting the ogr feature to a GEOSGeometry (without converting it to json and back). But this is the first solution that I could come up with.

import tempfile, json
from StringIO import StringIO
from osgeo import ogr
from django.contrib.gis.geos import GEOSGeometry

# Set testdata string
testdata = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark>
    <name>Simple placemark</name>
    <description>Attached to the ground. Intelligently places itself 
       at the height of the underlying terrain.</description>
    <Point>
      <coordinates>-122.0822035425683,37.42228990140251</coordinates>
    </Point>
  </Placemark>
</kml>"""

# Create tempfile for ogr driver read
temp = tempfile.NamedTemporaryFile()
temp.write(testdata)
temp.flush()

# Read XML file into python
driver = ogr.GetDriverByName('KML')
datasource = driver.Open(temp.name)
layer = datasource.GetLayer()
feat = layer.GetNextFeature()

# Convert ogr feature to GEOSGeometry
feat_json = json.loads(feat.ExportToJson())
feat_json['geometry']['coordinates'] = feat_json['geometry']['coordinates'][0:2]
geom = json.dumps(feat_json['geometry'])
pnt = GEOSGeometry(geom)

Then you get

print pnt
POINT (-122.0822035425682941 37.4222899014025074)