"""KML export for onX compatibility: track LineString + waypoint Placemarks.""" from __future__ import annotations import xml.etree.ElementTree as ET from typing import Optional from app.models.route import TrekkerRoute from app.models.trail_guide import TrailGuide KML_NS = "http://www.opengis.net/kml/2.2" def _desc_for_route(route: TrekkerRoute, guide: Optional[TrailGuide]) -> str: mi = route.stats.distance_m / 1609.344 gain = route.stats.elevation_gain_m * 3.28084 lines = [f"Distance: {mi:.1f} mi", f"Elevation gain: {gain:.0f} ft", f"Source: {route.source}"] for seg in route.segments: lines.append(f"Segment {seg.name}: max grade {seg.grade_pct_max:.1f}%") if guide: if guide.difficulty: lines.append(f"Difficulty: {guide.difficulty}") for wc in guide.water_crossings: depth = f" ({wc.depth_ft} ft)" if wc.depth_ft is not None else "" lines.append(f"Water crossing: {wc.name or 'unnamed'}{depth}") lines.extend(f"Warning: {w}" for w in guide.warnings) return "\n".join(lines) def write_kml(route: TrekkerRoute, trail_guide: Optional[TrailGuide] = None) -> str: kml = ET.Element("kml", {"xmlns": KML_NS}) doc = ET.SubElement(kml, "Document") ET.SubElement(doc, "name").text = route.name track = ET.SubElement(doc, "Placemark") ET.SubElement(track, "name").text = route.name ET.SubElement(track, "description").text = _desc_for_route(route, trail_guide) line = ET.SubElement(track, "LineString") ET.SubElement(line, "tessellate").text = "1" coords = " ".join( f"{p.lon:.7f},{p.lat:.7f},{p.ele if p.ele is not None else 0:.1f}" for p in route.points ) ET.SubElement(line, "coordinates").text = coords for w in route.waypoints: pm = ET.SubElement(doc, "Placemark") if w.name: ET.SubElement(pm, "name").text = w.name if w.desc: ET.SubElement(pm, "description").text = w.desc point = ET.SubElement(pm, "Point") ET.SubElement(point, "coordinates").text = ( f"{w.lon:.7f},{w.lat:.7f},{w.ele if w.ele is not None else 0:.1f}" ) return ET.tostring(kml, encoding="unicode", xml_declaration=True)