aboutsummaryrefslogtreecommitdiff
path: root/web/frontend/climb-map.ts
blob: 909614d85af65c328f2684d56f4f3b4d21ed42c0 (plain) (blame)
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

import type { Map as LeafletMap } from "leaflet";

interface ClimbMapPayload {
  distanceKm: number;
  elevations: number[];
  route?: [number, number][];
}

interface ClimbMapEndpoints {
  start: [number, number];
  end: [number, number];
  name: string;
}

const mountClimbMap = (): void => {
  const element = document.getElementById("climb-map");
  const endpointsElement = document.getElementById("climb-endpoints");
  const profileElement = document.getElementById("climb-profile-data");
  const leaflet = window.L;
  if (!element || !endpointsElement || !profileElement || !leaflet) return;
  const endpoints = JSON.parse(endpointsElement.textContent ?? "null") as ClimbMapEndpoints | null;
  const profile = JSON.parse(profileElement.textContent ?? "null") as ClimbMapPayload | null;
  if (!endpoints) return;
  const route = (profile?.route ?? []).map(([lon, lat]) => [lat, lon] as [number, number]);
  const line: [number, number][] = route.length > 1 ? route : [endpoints.start, endpoints.end];

  const map: LeafletMap = leaflet.map(element);
  leaflet
    .tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 19,
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    })
    .addTo(map);

  const startIcon = leaflet.divIcon({
    className: "ride-map-climb-start-icon",
    html: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="6" fill="currentColor"/></svg>',
    iconSize: [26, 26],
    iconAnchor: [13, 13],
  });
  const endIcon = leaflet.divIcon({
    className: "ride-map-climb-end-icon",
    html: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 3v18" stroke="currentColor" stroke-width="2"/><path d="M6 4h13v8H6Z" fill="currentColor"/><path d="M6 4h3.25v4H6ZM12.5 4h3.25v4H12.5ZM9.25 8h3.25v4H9.25ZM15.75 8H19v4h-3.25Z" fill="var(--color-forest)"/></svg>',
    iconSize: [26, 26],
    iconAnchor: [13, 13],
  });
  leaflet
    .polyline(line, {
      color: "var(--color-climb-route)",
      weight: 4,
      opacity: 0.9,
    })
    .addTo(map);
  leaflet
    .marker(endpoints.start, { icon: startIcon, alt: `${endpoints.name} start` })
    .addTo(map)
    .bindTooltip("Start");
  leaflet
    .marker(endpoints.end, { icon: endIcon, alt: `${endpoints.name} end` })
    .addTo(map)
    .bindTooltip("End");
  map.fitBounds(leaflet.latLngBounds(line), { padding: [40, 40], maxZoom: 16 });
};

mountClimbMap();