-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkml_utils.py
75 lines (62 loc) · 2.66 KB
/
kml_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import xml.etree.ElementTree as ET
import re
def kml_to_csv(file_path):
tree = ET.parse(file_path)
root = tree.getroot()
# Define the KML namespace
namespace = {'kml': 'http://earth.google.com/kml/2.1'}
# Find all Placemark elements
placemarks = root.findall(".//kml:Placemark", namespace)
results = []
for placemark in placemarks:
name_raw = placemark.find("kml:name", namespace).text if placemark.find("kml:name",
namespace) is not None else "Unknown"
coordinates = placemark.find(".//kml:coordinates", namespace).text.strip() if placemark.find(
".//kml:coordinates", namespace) is not None else "Unknown"
if coordinates == "Unknown":
print("Skip name", name_raw, "due to invalid coordinates")
lon, lat, _ = coordinates.split(',')
coordinates = (float(lat), float(lon))
# Extract name and elevation
match = re.search(r"\d+\.\s*(.*?)\s*\((\d+\.?\d*)\s*m\)", name_raw)
if match:
name = match.group(1)
meters = float(match.group(2))
else:
print("Skip name", name_raw, "due to invalid elevation")
continue
results.append((name, meters, coordinates))
with open('Highest.csv', 'w') as out:
for name, h, (lat, long) in results:
out.write(f"{name},{float(lat)},{float(long)},{float(h)}\n")
return results
def convert_wiki_csv(file_path):
with open(file_path, 'r') as f:
with open('MostProminent.csv', 'w') as out:
for line in f.readlines()[1:]:
name, coord, h = line.split(',')
coord = coord[:coord.index('(')]
coord = coord.split('/')[-1]
lat, long = coord.split(';')
out.write(f"{name},{float(lat)},{float(long)},{float(h)}\n")
def parse_csv(file_path):
results = []
with open(file_path, 'r') as f:
for line in f.readlines():
name, lat, lon, elevation = line.split(',')
results.append((name, float(elevation), (float(lat), float(lon))))
return results
def parse_coord_input(file_path):
if file_path.endswith('kml'):
return kml_to_csv(file_path)
elif file_path.endswith('csv'):
return parse_csv(file_path)
assert False
if __name__ == "__main__":
file_path = "data\\HighestPeaks.kml"
places = parse_coord_input(file_path)
for name, elevation, coords in places:
assert len(name) > 0
assert elevation > 2000.0, name
assert len(coords) == 2
print(f"Name: {name}\nMeters: {elevation} m\nCoordinates: {coords}\n")