Draw Simple Shapes in Google Earth Part 2

In the previous post we introduced the KML polygon feature and showed how it can be used to draw a square around liberty island in NY, now we will do the same thing using Python.

First let us transform our KML square example into a Cheetah template. If you are unfamiliar with Cheetah take a look here!


<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Style id="examplePolyStyle">
<PolyStyle>
<color>ff0000cc</color>
</PolyStyle>
</Style>
<Placemark>
<name>hollow box</name>
<styleUrl>#examplePolyStyle</styleUrl>
<Polygon>
<extrude>1</extrude>
<altitudeMode>clampToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
#for $vertex in $vertices
             $vertex[1],$vertex[0],0
         #end for
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Document>
</kml>


Notice how we replaced the hard coded vertices (coordinates) from the original KML file and replaced them with a Cheetah array and a for loop highlighted in blue text above.

And now the Code:
To actually use this template to generate a KML document lets define a simple Python function.


import geopy
from Cheetah.Template import Template

def createSquare(aLatLonCenter, aSize):
#parse the latlon string 
lLatLonCenter = geopy.util.parse_geo(aLatLonCenter)
lNECorner = geopy.distance.destination(lLatLonCenter, 45.0, aSize)
lSECorner = geopy.distance.destination(lLatLonCenter, 135.0, aSize)
lSWCorner = geopy.distance.destination(lLatLonCenter, 225.0, aSize)
lNWCorner = geopy.distance.destination(lLatLonCenter, 315.0, aSize)
lVertices = [lNECorner, lSECorner, lSWCorner, lNWCorner, lNECorner]

lTemplate = Template(file='kmlshapes.tmpl', searchList=[{'vertices': lVertices}])

return lTemplate


To test this code you can use a simple statement like this:

print createSquare('40 41m 23.50s N 74 2m 43.19s W', 0.250)

and you will get back a KML string defining a red square around Liberty island in NY.

Note: Geopy is used for parsing the Latitude / Longitude string as well as for calculating the corners of the square. Note also that KML polygon expects the last coordinate to be the same as the first, this is the reason for using 5 coordinates.

Next lets draw a circle using the same technique:

No comments: