aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/components/StopMapSheet.tsx
blob: a0d30f4a28fd297e27f9fbc596157a02c45a3746 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import maplibregl from "maplibre-gl";
import React, { useEffect, useMemo, useRef, useState } from "react";
import Map, { Marker, NavigationControl, type MapRef } from "react-map-gl/maplibre";
import { useApp } from "~/AppContext";
import { getLineColor } from "~/data/LineColors";
import type { RegionId } from "~/data/RegionConfig";
import type { Stop } from "~/data/StopDataProvider";
import { loadStyle } from "~/maps/styleloader";
import "./StopMapSheet.css";

export interface Position {
  latitude: number;
  longitude: number;
  orientationDegrees: number;
}

export interface ConsolidatedCirculationForMap {
  line: string;
  route: string;
  currentPosition?: Position;
}

interface StopMapProps {
  stop: Stop;
  circulations: ConsolidatedCirculationForMap[];
  region: RegionId;
}

export const StopMap: React.FC<StopMapProps> = ({
  stop,
  circulations,
  region,
}) => {
  const { theme } = useApp();
  const [styleSpec, setStyleSpec] = useState<any | null>(null);
  const mapRef = useRef<MapRef | null>(null);
  const hasFitBounds = useRef(false);

  useEffect(() => {
    let mounted = true;
    loadStyle("openfreemap", theme)
      .then((style) => {
        if (mounted) setStyleSpec(style);
      })
      .catch((err) => console.error("Failed to load map style", err));
    return () => {
      mounted = false;
    };
  }, [theme]);

  const center = useMemo(() => {
    if (stop.latitude && stop.longitude) {
      return { latitude: stop.latitude, longitude: stop.longitude };
    }
    // fallback to first available bus position
    const pos = circulations.find((c) => c.currentPosition)?.currentPosition;
    return pos
      ? { latitude: pos.latitude, longitude: pos.longitude }
      : { latitude: 42.2406, longitude: -8.7207 }; // Vigo approx fallback
  }, [stop.latitude, stop.longitude, circulations]);

  const busPositions = useMemo(
    () => circulations.filter((c) => !!c.currentPosition),
    [circulations],
  );

  // Fit bounds to stop + buses, with ~1km padding each side, with a modest animation
  // Only fit bounds on the first load, not on subsequent updates
  useEffect(() => {
    if (!styleSpec || !mapRef.current || hasFitBounds.current) return;

    const points: { lat: number; lon: number }[] = [];
    if (stop.latitude && stop.longitude) {
      points.push({ lat: stop.latitude, lon: stop.longitude });
    }
    for (const c of busPositions) {
      if (c.currentPosition) {
        points.push({
          lat: c.currentPosition.latitude,
          lon: c.currentPosition.longitude,
        });
      }
    }
    if (points.length === 0) return;

    let minLat = points[0].lat,
      maxLat = points[0].lat,
      minLon = points[0].lon,
      maxLon = points[0].lon;
    for (const p of points) {
      if (p.lat < minLat) minLat = p.lat;
      if (p.lat > maxLat) maxLat = p.lat;
      if (p.lon < minLon) minLon = p.lon;
      if (p.lon > maxLon) maxLon = p.lon;
    }

    // ~1km in degrees
    const kmToDegLat = 1.0 / 111.32; // ≈0.008983
    const centerLat = (minLat + maxLat) / 2;
    const kmToDegLon = kmToDegLat / Math.max(Math.cos((centerLat * Math.PI) / 180), 0.1);
    const padLat = kmToDegLat;
    const padLon = kmToDegLon;

    const sw = [minLon - padLon, minLat - padLat] as [number, number];
    const ne = [maxLon + padLon, maxLat + padLat] as [number, number];
    const bounds = new maplibregl.LngLatBounds(sw, ne);

    try {
      mapRef.current.fitBounds(bounds, {
        padding: 32,
        duration: 700,
        maxZoom: 17,
      } as any);
      hasFitBounds.current = true;
    } catch {}
  }, [styleSpec, stop.latitude, stop.longitude, busPositions]);

  return (
    <div className="stop-map-container">
      {styleSpec && (
        <Map
          mapLib={maplibregl as any}
          initialViewState={{
            latitude: center.latitude,
            longitude: center.longitude,
            zoom: 16,
          }}
          style={{ width: "100%", height: "100%" }}
          mapStyle={styleSpec}
          attributionControl={false}
          ref={mapRef}
        >
          <NavigationControl position="top-left" />

          {/* Stop marker (center) */}
          {stop.latitude && stop.longitude && (
            <Marker
              longitude={stop.longitude}
              latitude={stop.latitude}
              anchor="bottom"
            >
              <div
                style={{
                  width: 14,
                  height: 14,
                  background: "#1976d2",
                  border: "2px solid white",
                  borderRadius: "50%",
                  boxShadow: "0 0 0 2px rgba(0,0,0,0.2)",
                }}
                title={`Stop ${stop.stopId}`}
              />
            </Marker>
          )}

          {/* Bus markers with heading */}
          {busPositions.map((c, idx) => {
            const p = c.currentPosition!;
            const lineColor = getLineColor(region, c.line);
            return (
              <Marker
                key={idx}
                longitude={p.longitude}
                latitude={p.latitude}
                anchor="center"
              >
                <div
                  title={`${c.line}  ${c.route}`}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    gap: 2,
                    transform: `rotate(${p.orientationDegrees}deg)`,
                    transformOrigin: "center center",
                  }}
                >
                  {/* Line number above */}
                  <div
                    style={{
                      background: lineColor.background,
                      color: lineColor.text,
                      padding: "2px 4px",
                      borderRadius: 4,
                      fontSize: 10,
                      fontWeight: 700,
                      lineHeight: 1,
                      border: "1px solid #fff",
                      boxShadow: "0 1px 2px rgba(0,0,0,0.3)",
                    }}
                  >
                    {c.line}
                  </div>
                  {/* Arrow pointing direction */}
                  <svg
                    width="20"
                    height="20"
                    viewBox="0 0 24 24"
                    style={{
                      filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.3))",
                    }}
                  >
                    <path
                      d="M12 2 L20 22 L12 18 L4 22 Z"
                      fill={lineColor.background}
                      stroke="#fff"
                      strokeWidth="1.5"
                    />
                  </svg>
                </div>
              </Marker>
            );
          })}
        </Map>
      )}
    </div>
  );
};