import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { GNSS_ICON } from "/js/icons.js"; import { isLoggedIn } from "/js/auth.js"; import { onGnssFollow } from "/js/panels.js"; const POSITION_URL = "/api/gnss/position"; const POLL_INTERVAL_MS = 1500; const JUMP_M = 1000; // farther than this from the marker: jump there, not glide (a new simulation) // The position as an arrow, turned by the course once there is one. const ARROW = ``; // A sidebar icon that polls /api/gnss/position (the car's receiver, fed // server-side into GNSS_LATEST in app.rb) and shows the fix as a // marker, with fix status in a flyout. Polling rather than a push channel // is deliberate — see the comment in app.rb next to GNSS_LATEST — and fits // a receiver's ~1Hz report rate fine. // One follow step for a moving position (this receiver, the browser's own // geolocation). In the 3D (pitched) view it turns heading-up like a car // navigation, with the position in the lower part of the screen; the last // heading stays while standing still (speed in m/s, heading in degrees). // duration (ms): a linear glide over that long — the time until the next // fix, so a 1 Hz receiver moves the camera smoothly, not in 10 m jumps. // Moving the map by hand (drag, zoom, rotate, tilt) pauses the follow, as a // car navigation does — to look around, change the route — the position // keeps moving; "Back to the position" or FREE_LOOK_MS without touching the // map resumes it. const FREE_LOOK_MS = 15000; const FOLLOWING_MS = 5000; // a follow step this recently: the map is following const freeLook = new WeakMap(); // map -> { until, button } function freeLookState(map) { let state = freeLook.get(map); if (state) return state; const button = document.createElement("button"); button.type = "button"; button.className = "follow-resume"; button.textContent = "Back to the position"; button.hidden = true; map.getContainer().appendChild(button); state = { until: 0, button, followedAt: 0 }; button.addEventListener("click", () => resumeFollow(map)); const touched = (e) => { // our own easeTo, or nothing being followed (GNSS off) if (e.originalEvent && Date.now() - state.followedAt <= FOLLOWING_MS) pauseFollow(map); }; for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched); freeLook.set(map, state); return state; } // Also for a view the app moves to itself (the driving bar's route overview). export function pauseFollow(map) { const state = freeLookState(map); state.until = Date.now() + FREE_LOOK_MS; state.button.hidden = false; clearTimeout(state.timer); state.timer = setTimeout(() => (state.button.hidden = true), FREE_LOOK_MS); } // Is the map following a position right now (a follow step lately, not // paused by hand)? For the driving bar's recenter button. export function isFollowing(map) { const state = freeLookState(map); return Date.now() - state.followedAt <= FOLLOWING_MS && Date.now() >= state.until; } export function resumeFollow(map) { const state = freeLookState(map); state.until = 0; state.button.hidden = true; clearTimeout(state.timer); } // The first step of a follow (or a jump after a gap): zoom in to see the // road ahead. easeTo, not flyTo — flyTo's swoop zooms out over the distance // first, the wrong way when starting to drive. export const FOLLOW_ZOOM = 16; export function startFollow(map, lngLat) { map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), FOLLOW_ZOOM), duration: 1000 }); } export function followPosition(map, lngLat, heading, speed, duration) { const free = freeLookState(map); free.followedAt = Date.now(); // following in 3D like a navigation: the overview map out of the way // (style.css), back once the follow stops or the view goes 2D document.documentElement.classList.toggle("follow-3d", map.getPitch() > 0); clearTimeout(free.followTimer); free.followTimer = setTimeout(() => document.documentElement.classList.remove("follow-3d"), FOLLOWING_MS); if (Date.now() < free.until) return; free.button.hidden = true; const pitched = map.getPitch() > 0; const moving = Number.isFinite(heading) && (speed ?? 0) >= 1; const zoom = moving && autoZoom(map.getZoom(), speed); map.easeTo({ center: lngLat, padding: { top: pitched ? map.getContainer().clientHeight * 0.4 : 0 }, ...(pitched && moving && { bearing: heading }), ...(zoom && { zoom }), ...(duration != null && { duration, easing: (t) => t }), }); } // Auto-zoom like a car navigation: close in town, farther out the faster // (0 km/h z17, 50 z16.2, 90 z15.6, 130+ z15). Eased toward that by at most // 0.15 a fix and ignored within 0.25, so speed jitter doesn't pump the map. // A hand zoom pauses the follow; on resuming it eases back. export function autoZoom(current, speed) { const target = Math.min(17, Math.max(15, 17 - speed * 3.6 * 0.0154)); const diff = target - current; if (Math.abs(diff) < 0.25) return null; return current + Math.sign(diff) * Math.min(Math.abs(diff), 0.15); } // Meters between a MapLibre LngLat and [lon, lat] (equirectangular). function distanceM({ lng, lat }, [lon2, lat2]) { return Math.hypot((lon2 - lng) * Math.cos((lat * Math.PI) / 180), lat2 - lat) * 111320; } // The marker moved to lngLat the same way: a linear glide over duration ms. function glideMarker(marker, lngLat, duration) { cancelAnimationFrame(marker._glide); const from = marker.getLngLat(); const start = performance.now(); const step = (now) => { const t = Math.min(1, (now - start) / duration); marker.setLngLat([from.lng + (lngLat[0] - from.lng) * t, from.lat + (lngLat[1] - from.lat) * t]); if (t < 1) marker._glide = requestAnimationFrame(step); }; marker._glide = requestAnimationFrame(step); } export class GnssControl { constructor(map) { this._map = map; this._marker = null; this._timer = null; this._enabled = false; this._enabledListeners = []; } // Read by LocateControl: if it's mid-tracking on the browser-geolocation // fallback when GNSS turns on, GNSS should take over there and then, not // only the next time the button happens to get clicked — the browser's // own (often less accurate) position has no business still being used // once the app's own receiver has a fix. onEnabledChange(callback) { this._enabledListeners.push(callback); } mount(sidebar) { this._container = document.createElement("div"); this._container.className = "sidebar-item"; this._container.innerHTML = ` `; this._icon = this._container.querySelector(".sidebar-icon"); this._flyout = this._container.querySelector(".sidebar-flyout"); this._status = this._container.querySelector(".gnss-control__status"); this._icon.addEventListener("click", () => this._setEnabled(!this._enabled)); onGnssFollow(() => !this._enabled && !this._container.hidden && this._setEnabled(true)); // GET /api/gnss/position itself requires login too (app.rb) — hidden // here rather than shown and failing on click, same reasoning as // gpx.js's write-action controls: it reveals where the receiver // physically is, not something to leave open to anyone with the URL. if (!isLoggedIn()) this._container.hidden = true; sidebar.appendChild(this._container); } _setEnabled(enabled) { this._enabled = enabled; this._icon.classList.toggle("active", enabled); this._flyout.hidden = !enabled; if (enabled) { this._poll(); this._timer = setInterval(() => this._poll(), POLL_INTERVAL_MS); } else { this._stopPolling(); this._removeMarker(); this._status.textContent = ""; } this._enabledListeners.forEach((callback) => callback(enabled)); } _stopPolling() { if (this._timer) { clearInterval(this._timer); this._timer = null; } } async _poll() { let data; try { const response = await fetch(POSITION_URL); data = await response.json(); } catch (err) { this._status.textContent = "unreachable"; return; } if (!data.available) { this._removeMarker(); this._status.textContent = "no fix"; return; } // no fix, carried along the route (a tunnel: App.gnss_position) this._status.textContent = data.estimated ? "estimated (no fix)" : fixLabel(data); const lngLat = [data.lon, data.lat]; // Recenters on every fix while enabled — this is the app's own // receiver, so "GNSS on" means "follow it", the same way LocateControl // (public/js/locate.js) follows it when GNSS is what it's using too. // startFollow (zooming in) only for the first fix, since that's the // one jumping from wherever the map already was; a plain follow for // later updates, zooming by the speed (autoZoom). const far = this._marker && distanceM(this._marker.getLngLat(), lngLat) > JUMP_M; if (far) this._removeMarker(); if (!this._marker) { const el = document.createElement("div"); el.className = "gnss-marker"; // MapLibre markers are plain positioned DOM elements, not tied to the // style's sources/layers, so — unlike the radar/GPX layers — this // survives map.setStyle() (switching Online/Offline) with no extra // re-add handling needed. this._marker = new Marker({ element: el, rotationAlignment: "map", pitchAlignment: "map" }).setLngLat(lngLat).addTo(this._map); startFollow(this._map, lngLat); } else { glideMarker(this._marker, lngLat, POLL_INTERVAL_MS); followPosition(this._map, lngLat, data.track, data.speed, POLL_INTERVAL_MS); } // an arrow turned by the course, once there is one (a dot until then) if (Number.isFinite(data.track)) { const el = this._marker.getElement(); if (!el.classList.contains("gnss-marker--arrow")) { el.classList.add("gnss-marker--arrow"); el.innerHTML = ARROW; } this._marker.setRotation(data.track); } this._marker.getElement().classList.toggle("gnss-marker--estimated", !!data.estimated); } _removeMarker() { if (this._marker) { this._marker.remove(); this._marker = null; } } // Read by LocateControl: GNSS is only ever used for "find my location" // when explicitly turned on here — clicking Locate while this is off // falls back to the browser's own geolocation instead, rather than // silently switching sources on whatever GET /api/gnss/position happens // to report at that moment. isEnabled() { return this._enabled; } // The current fix, if any — null both when disabled and when enabled // but not fixed yet (no marker placed either way). getPosition() { return this._marker ? this._marker.getLngLat() : null; } } function fixLabel({ mode, eph }) { const kind = mode === 3 ? "3D" : mode === 2 ? "2D" : "no fix"; return eph ? `${kind} (±${Math.round(eph)}m)` : kind; }