Skip to content

Instantly share code, notes, and snippets.

@hobbes3
Last active September 10, 2019 23:35
Show Gist options
  • Save hobbes3/1023099f0c6f56457c4089c358af688e to your computer and use it in GitHub Desktop.
Save hobbes3/1023099f0c6f56457c4089c358af688e to your computer and use it in GitHub Desktop.
KML get centroid
#!/usr/bin/env python
# hobbes3
import xml.etree.ElementTree as ET
import csv
from statistics import mean
KML_FILE = "sf_blocks.kml"
CSV_FILE = "sf_blocks_lat_lon.csv"
CSV_COLUMNS = ["BLKLOT", "lat", "lon"]
tree = ET.parse(KML_FILE)
centroids = []
for placemark in tree.iter("Placemark"):
blklot = placemark.find(".//Data[@name='blklot']/value").text
coords = placemark.find(".//coordinates").text.strip().split("\n")
lats = []
lons = []
print("BLKLOT: {}".format(blklot))
for coord in coords:
lats.append(float(coord.split(",")[1]))
lons.append(float(coord.split(",")[0]))
# import pdb; pdb.set_trace()
c_lat = mean(lats)
c_lon = mean(lons)
print("Centroid: {}, {}".format(blklot, c_lat, c_lon))
centroids.append({
"BLKLOT": blklot,
"lat": c_lat,
"lon": c_lon,
})
try:
with open(CSV_FILE, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=CSV_COLUMNS)
writer.writeheader()
for centroid in centroids:
writer.writerow(centroid)
except IOError:
print("I/O error")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment