Skip to content

Instantly share code, notes, and snippets.

@agocs
Last active December 11, 2015 13:48
Show Gist options
  • Save agocs/4609737 to your computer and use it in GitHub Desktop.
Save agocs/4609737 to your computer and use it in GitHub Desktop.
Easy way to find the centroid of a bunch of placemarks from a KML file.
from xml.dom.minidom import parseString
def findCentroidGivenKML(location):
#Read KML file as a string
file = open(location)
data = file.read()
file.close()
#Parse that string into a DOM
dom = parseString(data)
#initialize latitude and longitude lists
latitudes = []
longitudes = []
#Iterate through a collection of coordinates elements
for d in dom.getElementsByTagName('coordinates'):
#Break them up into latitude and longitude
coords = d.firstChild.data.split(',')
longitudes.append(float(coords[0]))
latitudes.append(float(coords[1]))
#find the centroid
centerLatitude = sum(latitudes)/len(latitudes)
centerLongitude = sum(longitudes)/len(longitudes)
return ([centerLongitude,centerLatitude])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment