Last active
September 10, 2019 23:35
-
-
Save hobbes3/1023099f0c6f56457c4089c358af688e to your computer and use it in GitHub Desktop.
KML get centroid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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