Dashboard: altitude (gnss.alt, the terrain's while simulating), the car tilted by the terrain's slope while simulating; free look while following (the map moved by hand pauses the follow, "Back to the position" or 15 s resumes it); overlays and shown library files remembered per device (localStorage), back after a reload once the offline checks are in
CI / check (push) Successful in 24s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-01 00:15:08 +01:00
1 parent 8c999919b8
commit 12b4ac6725
9 files changed
+199 -19

No files matched your search

+40 -4
View File
@@ -1,5 +1,6 @@
import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.js";
import { elevationAt } from "/js/dem.js";
// The car's dashboard over the map, off the CAN signals (GET /api/can,
// names from data/can.json): one inclinometer — compass ring around a rear
@@ -9,10 +10,15 @@ import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.js
// Heading: driving, the GNSS course (from consecutive fixes); standing
// still, the compass (imu.heading, once the node sends it) — else the
// last course stays, dimmed.
const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" };
const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", alt: "gnss.alt", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" };
const MOVING_MS = 1.5; // m/s: above this the GNSS course counts
const COURSE_MIN_M = 5; // fixes closer than this: too noisy for a course
const POLL_MS = 500;
// Simulated tilt: the terrain's slope along the course (pitch) and across
// it (roll), from the DEM 2·TILT_HALF_M apart — the terrain, not the road:
// a road cut into a hillside is flatter across than this reads.
const TILT_ZOOM = 12; // ~20–40 m pixels (offline terrain goes to 13)
const TILT_HALF_M = 15;
const STALE_S = 5; // older signal: shown as missing
const WARN = { roll: 20, pitch: 25 }; // ° — amber past these, red past 1.5×
const STORE_KEY = "maptool.dashboard";
@@ -31,7 +37,7 @@ const REROUTE_EVERY_MS = 15000;
const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving
const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart
const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true, banner: true };
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true };
const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely
const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through
@@ -164,6 +170,31 @@ export class DashboardControl {
this._rerouteAt = 0;
}
// What the simulation doesn't send, from the terrain at its position: the
// altitude, and pitch / roll in degrees (nose up and right side down
// positive, as the inclinometer draws them) — unless a node sends them.
async _simulateTerrain() {
const { lat, lon } = this._values;
if (lat == null) return;
this._offlineTerrain ??= fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => d.available).catch(() => false);
const offline = await this._offlineTerrain;
const rad = Math.PI / 180;
const at = (bearing) => {
const dx = TILT_HALF_M * Math.sin(bearing * rad);
const dy = TILT_HALF_M * Math.cos(bearing * rad);
return elevationAt(lon + dx / (111320 * Math.cos(lat * rad)), lat + dy / 111320, offline, { zoom: TILT_ZOOM, smooth: true });
};
if (this._values.alt == null) {
this._values.alt = await elevationAt(lon, lat, offline, { zoom: TILT_ZOOM, smooth: true });
}
if (this._course == null || this._values.pitch != null || this._values.roll != null) return;
const [front, back, right, left] = await Promise.all([0, 180, 90, 270].map((b) => at(this._course + b)));
if ([front, back, right, left].includes(null)) return;
const deg = (rise) => Math.atan(rise / (2 * TILT_HALF_M)) / rad;
this._values.pitch = deg(front - back);
this._values.roll = deg(left - right);
}
// The limit and what's ahead: from the route while on it, else the road.
_navigate() {
const { lat, lon, speed } = this._values;
@@ -237,6 +268,7 @@ export class DashboardControl {
<div class="overlays-panel__details" hidden>
<label class="live-tracker__row"><input type="checkbox" data-widget="inclinometer"> Inclinometer &amp; compass</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="speed"> Speed</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="altitude"> Altitude</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="navigation"> Speed limit &amp; ahead (route)</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="banner"> Navigation banner (next turn)</label>
<label class="live-tracker__row">Background <input type="range" class="dash-opacity" min="0" max="1" step="0.05"></label>
@@ -307,7 +339,7 @@ export class DashboardControl {
this._card = document.createElement("div");
this._card.className = "dash-card";
this._card.style.setProperty("--dash-alpha", this._settings.opacity ?? DEFAULT_OPACITY);
this._card.innerHTML = `<div class="dash-nav"><div class="dash-limit"></div><div class="dash-ahead"></div></div>${INCLINOMETER}<div class="dash-speed"><span></span> km/h</div>`;
this._card.innerHTML = `<div class="dash-nav"><div class="dash-limit"></div><div class="dash-ahead"></div></div>${INCLINOMETER}<div class="dash-speed"><span></span> km/h</div><div class="dash-alt"><span></span> m</div>`;
this._map.getContainer().appendChild(this._card);
// the next turn across the top, as in a car navigation
this._banner = document.createElement("div");
@@ -341,6 +373,7 @@ export class DashboardControl {
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
}));
this._updateCourse(this._values);
if (this._simRunning) await this._simulateTerrain();
this._navigate();
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
this._status.hidden = !this._status.textContent;
@@ -363,7 +396,10 @@ export class DashboardControl {
speed.style.display = widgets.speed ? "" : "none";
const nav = this._card.querySelector(".dash-nav");
nav.style.display = widgets.navigation ? "" : "none";
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.navigation;
const alt = this._card.querySelector(".dash-alt");
alt.style.display = widgets.altitude ? "" : "none";
alt.querySelector("span").textContent = v.alt == null ? "—" : Math.round(v.alt);
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.altitude && !widgets.navigation;
this._renderNav(nav);
this._renderBanner();
+18 -6
View File
@@ -63,12 +63,24 @@ function fetchTile(z, x, y, offlineAvailable) {
// -> Promise<number|null> — null on a fetch/decode failure, or a point
// falling outside a partial offline extract's zoom range.
export async function elevationAt(lng, lat, offlineAvailable) {
const { tileX, tileY, fracX, fracY } = lngLatToTile(lng, lat, DEM_ZOOM);
const tile = await fetchTile(DEM_ZOOM, tileX, tileY, offlineAvailable);
// smooth: bilinear between the four pixels around the point (within the
// tile) instead of the nearest one — for slopes over a few meters, where
// nearest-pixel steps would read as 0° then a jump.
export async function elevationAt(lng, lat, offlineAvailable, { zoom = DEM_ZOOM, smooth = false } = {}) {
const { tileX, tileY, fracX, fracY } = lngLatToTile(lng, lat, zoom);
const tile = await fetchTile(zoom, tileX, tileY, offlineAvailable);
if (!tile) return null;
const px = Math.min(tile.size - 1, Math.floor(fracX * tile.size));
const py = Math.min(tile.size - 1, Math.floor(fracY * tile.size));
return tile.elevations[py * tile.size + px];
const { elevations: e, size } = tile;
if (!smooth) {
const px = Math.min(size - 1, Math.floor(fracX * size));
const py = Math.min(size - 1, Math.floor(fracY * size));
return e[py * size + px];
}
const x = Math.min(size - 1.001, Math.max(0, fracX * size - 0.5));
const y = Math.min(size - 1.001, Math.max(0, fracY * size - 0.5));
const [x0, y0] = [Math.floor(x), Math.floor(y)];
const [tx, ty] = [x - x0, y - y0];
const at = (i, j) => e[(y0 + j) * size + x0 + i];
return (at(0, 0) * (1 - tx) + at(1, 0) * tx) * (1 - ty) + (at(0, 1) * (1 - tx) + at(1, 1) * tx) * ty;
}
+40
View File
@@ -20,7 +20,47 @@ const ARROW = `<svg viewBox="0 0 24 24" width="26" height="26"><path d="M12 2 L2
// 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", () => {
state.until = 0;
button.hidden = true;
clearTimeout(state.timer);
});
const touched = (e) => {
// our own easeTo, or nothing being followed (GNSS off)
if (!e.originalEvent || Date.now() - state.followedAt > FOLLOWING_MS) return;
state.until = Date.now() + FREE_LOOK_MS;
button.hidden = false;
clearTimeout(state.timer);
state.timer = setTimeout(() => (button.hidden = true), FREE_LOOK_MS);
};
for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched);
freeLook.set(map, state);
return state;
}
export function followPosition(map, lngLat, heading, speed, duration) {
const free = freeLookState(map);
free.followedAt = Date.now();
if (Date.now() < free.until) return;
free.button.hidden = true;
const pitched = map.getPitch() > 0;
const moving = Number.isFinite(heading) && (speed ?? 0) >= 1;
map.easeTo({
+17
View File
@@ -37,6 +37,7 @@ const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge
// folders, as opposed to an OS file drag (type "Files") for uploading a new
// one — both land on the same drop targets, told apart by this.
const MOVE_MIME = "application/x-gpx-path";
const GPX_VISIBLE_KEY = "gpxVisible";
const FOLDER_DRAG_PREFIX = "folder:"; // a dragged folder's MOVE_MIME payload, vs. a node key
// A sidebar icon that opens a side panel for uploading GPX files (via
@@ -601,7 +602,23 @@ export class GpxPanelControl {
if (feature) this._openPointPopup(path, feature, [lng, lat]);
}
// The shown files, per device (localStorage) — back after a reload by restore().
_saveVisible() {
try { localStorage.setItem(GPX_VISIBLE_KEY, JSON.stringify([...this._visible])); } catch { /* private window: not kept */ }
}
async restore() {
let paths = [];
try { paths = JSON.parse(localStorage.getItem(GPX_VISIBLE_KEY)) || []; } catch { /* nothing kept */ }
await Promise.all(paths.map((path) => this.show(path)));
}
async _toggleFile(path, visible, checkbox) {
await this._toggleFileOnly(path, visible, checkbox);
this._saveVisible();
}
async _toggleFileOnly(path, visible, checkbox) {
if (visible) {
this._visible.add(path);
const ok = await this._addLayers(path);
+21 -8
View File
@@ -578,7 +578,8 @@ function applyStyle(name) {
// switch to), so it's removed entirely rather than left sitting there
// offering a choice that can't work.
const offlineStatus = document.querySelector(".topbar__offline-status");
fetch("/api/offline-tiles")
const ready = [];
ready.push(fetch("/api/offline-tiles")
.then((response) => response.json())
.then(({ available }) => {
if (available) {
@@ -594,25 +595,37 @@ fetch("/api/offline-tiles")
// Backend check failed; keep the online style and leave the switch as
// is rather than guessing — this is the same-origin request itself
// failing, not evidence offline tiles are actually unavailable.
});
}));
fetch("/api/terrain-tiles")
ready.push(fetch("/api/terrain-tiles")
.then((response) => response.json())
.then(({ available }) => {
overlaysControl.setHillshadeOfflineAvailable(available);
overlaysControl.setShadowOfflineAvailable(available);
})
.catch(() => {});
.catch(() => {}));
fetch("/api/hiking-trails")
ready.push(fetch("/api/hiking-trails")
.then((response) => response.json())
.then(({ countries, bboxes }) => overlaysControl.setHikingTrailsOfflineCountries(countries, bboxes))
.catch(() => {});
.catch(() => {}));
fetch("/api/kiwix")
ready.push(fetch("/api/kiwix")
.then((response) => response.json())
.then(({ available }) => overlaysControl.setWikiAvailable(available))
.catch(() => {});
.catch(() => {}));
// What was on before the reload / update (localStorage, per device): once
// the checks above are in (offline or online terrain, trails, wiki) and the
// base map they switched to has loaded.
Promise.allSettled(ready).then(() => {
const restore = () => {
overlaysControl.restore();
gpxPanel.restore();
};
if (map.loaded()) restore();
else map.once("idle", restore);
});
// Alt+click, right click or a long press (touch browsers fire
// contextmenu for it) anywhere shows every rendered feature at that point — base map
+32
View File
@@ -189,6 +189,12 @@ class HillshadeControl {
// here since neither has anything to "manage," just on/off (Radar's own
// scrub/forecast controls live behind expanding its item, not a factor in
// where it's mounted).
const OVERLAYS_ON_KEY = "overlaysOn";
function readOn() {
try { return JSON.parse(localStorage.getItem(OVERLAYS_ON_KEY)) || {}; } catch { return {}; }
}
export class OverlaysControl {
constructor(map) {
this._map = map;
@@ -246,6 +252,7 @@ export class OverlaysControl {
li.className = `overlays-panel__item${expandable ? " overlays-panel__item--expandable" : ""}`;
list.appendChild(li);
mount(li);
this._remember(li, `${heading}/${li.querySelector(".overlays-panel__name, label")?.textContent.trim()}`);
}
}
@@ -254,6 +261,31 @@ export class OverlaysControl {
sidebar.appendChild(this._container);
}
// Which overlays are on, per device (localStorage), so a reload or an
// update doesn't switch them all off: saved on every change, turned back
// on by restore() — once map.js knows what's available offline.
_remember(li, key) {
const toggle = li.querySelector(".overlays-panel__toggle");
if (!toggle) return;
(this._toggles ??= []).push([key, toggle, li]);
toggle.addEventListener("change", () => {
const on = readOn();
if (toggle.checked) on[key] = true;
else delete on[key];
try { localStorage.setItem(OVERLAYS_ON_KEY, JSON.stringify(on)); } catch { /* private window: not kept */ }
});
}
restore() {
const on = readOn();
for (const [key, toggle, li] of this._toggles ?? []) {
const hidden = toggle.closest("[hidden]"); // within the item: not for this login (the closed panel doesn't count)
if (!on[key] || toggle.checked || toggle.disabled || (hidden && li.contains(hidden))) continue;
toggle.checked = true;
toggle.dispatchEvent(new Event("change"));
}
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;