Draw Simple Shapes in Google Earth Part 3 (Draw a Circle)

In the previous post we showed how python can be used to draw squares in Google Earth using KML, now we will show how we can draw circles using the same technique.

Again, 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>

Again, 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 createCircle(aLatLonCenter, aDiameter):
lLatLonCenter = geopy.util.parse_geo(aLatLonCenter)
lVertices = []
lAngle = 0
lRadius = aDiameter / 2.0
while lAngle <= 360:
lVertex = geopy.distance.destination(lLatLonCenter, lAngle, lRadius)
lVertices.append(lVertex)
lAngle = lAngle + 10

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

return lTemplate



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

print createCircle('40 41m 23.50s N 74 2m 43.19s W', 1.0)

and you will get back a KML string defining a red circle 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.
Back to the start of this tutorial!

No comments: