Tracker and ITS-G5 as separate overlays, Overlays grouped by category: the tracker gets a name/icon/color, charging from its USB power topic, a floating info card (per-device opacity), a trail of the last 1–24 h and optional position logging that survives restarts (LiveStore); hiking trails keep their main checkbox as an all-countries toggle
This commit is contained in:
1 parent
3fc8c75c60
commit
0e5f79f8e4
9 files changed
+801
-205
No files matched your search
@@ -2119,6 +2119,20 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Category headings between the Overlays items (overlays.js). */
|
||||
.overlays-panel__group {
|
||||
margin: 10px 4px 2px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.overlays-panel__group:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.overlays-panel__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -2993,3 +3007,88 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Tracker overlay settings (live.js). */
|
||||
.live-tracker__settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* Same "author display wins over the UA [hidden] rule" gotcha as
|
||||
.gpx-panel__action[hidden]. */
|
||||
.live-tracker__settings[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.live-tracker__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.live-tracker__row input[type="range"] {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.live-tracker__name-input {
|
||||
padding: 4px 6px;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.live-tracker__save {
|
||||
align-self: flex-start;
|
||||
padding: 4px 14px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* The tracker's floating info card over the map (per-device opacity). */
|
||||
.live-tracker-card {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
bottom: 36px;
|
||||
z-index: 3;
|
||||
min-width: 170px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.25);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.live-tracker-card__title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 4px;
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.live-tracker-card__icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 5px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.live-tracker-card__icon svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.live-tracker-card th {
|
||||
padding-right: 10px;
|
||||
color: #666;
|
||||
font-weight: normal;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -202,7 +202,10 @@ export class HikingTrailsControl {
|
||||
this._details = li.querySelector(".overlays-panel__details");
|
||||
this._countryList = li.querySelector(".hiking-trail-countries");
|
||||
|
||||
this._checkbox.addEventListener("change", (event) => this._toggleOnline(event.target.checked));
|
||||
this._checkbox.addEventListener("change", (event) => {
|
||||
if (this._offlineCountries.length) this._toggleAllCountries(event.target.checked);
|
||||
else this._toggleOnline(event.target.checked);
|
||||
});
|
||||
this._nameButton.addEventListener("click", () => {
|
||||
if (this._offlineCountries.length === 0) return; // nothing to expand into yet
|
||||
const expanding = this._details.hidden;
|
||||
@@ -222,7 +225,10 @@ export class HikingTrailsControl {
|
||||
if (countries.length === 0) return;
|
||||
|
||||
if (this._active) this._toggleOnline(false);
|
||||
this._checkbox.hidden = true;
|
||||
// The main checkbox stays: offline it switches every country at once
|
||||
// (indeterminate while only some are on); the name opens the list.
|
||||
this._checkbox.checked = false;
|
||||
this._checkbox.title = "All countries — click the name to pick some";
|
||||
|
||||
this._countryList.innerHTML = countries
|
||||
.map(
|
||||
@@ -237,7 +243,10 @@ export class HikingTrailsControl {
|
||||
)
|
||||
.join("");
|
||||
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
|
||||
input.addEventListener("change", (event) => this._toggleCountry(event.target.value, event.target.checked));
|
||||
input.addEventListener("change", (event) => {
|
||||
this._toggleCountry(event.target.value, event.target.checked);
|
||||
this._syncMainCheckbox();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -247,6 +256,23 @@ export class HikingTrailsControl {
|
||||
if (!input || input.checked) return;
|
||||
input.checked = true;
|
||||
this._toggleCountry(code, true);
|
||||
this._syncMainCheckbox();
|
||||
}
|
||||
|
||||
_toggleAllCountries(active) {
|
||||
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
|
||||
if (input.checked === active) return;
|
||||
input.checked = active;
|
||||
this._toggleCountry(input.value, active);
|
||||
});
|
||||
this._syncMainCheckbox();
|
||||
}
|
||||
|
||||
_syncMainCheckbox() {
|
||||
const inputs = [...this._countryList.querySelectorAll(".hiking-trail-countries__toggle")];
|
||||
const on = inputs.filter((input) => input.checked).length;
|
||||
this._checkbox.checked = on > 0 && on === inputs.length;
|
||||
this._checkbox.indeterminate = on > 0 && on < inputs.length;
|
||||
}
|
||||
|
||||
_toggleOnline(active) {
|
||||
|
||||
+387
-146
@@ -1,18 +1,17 @@
|
||||
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
||||
import { NPS_SYMBOLS, MAP_MARKER_ICON } from "/js/icons.js";
|
||||
import { NPS_SYMBOLS, POI_ICONS, MAP_MARKER_ICON } from "/js/icons.js";
|
||||
import { svgToImageData, badgeImageId, escapeHtml } from "/js/gpx.js";
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { PointStyleFields } from "/js/notes.js";
|
||||
|
||||
// The car's live data off the home MQTT broker (app.rb's /api/live): its
|
||||
// position from the LTE GNSS tracker, and the ITS-G5 stations its receiver
|
||||
// hears. An Overlays item; polled like the GNSS control, since the server
|
||||
// side only holds the latest state anyway.
|
||||
// Live data off the home MQTT broker (app.rb's /api/live, LiveStore): two
|
||||
// Overlays items, "Tracker" (the GNSS tracker: position, trail, an optional
|
||||
// floating info card) and "ITS-G5" (stations its receiver hears). One
|
||||
// shared poller feeds both, running only while either is on.
|
||||
|
||||
const SOURCE_ID = "live-points";
|
||||
const POLL_INTERVAL_MS = 2000;
|
||||
const VEHICLE_COLOR = "#1a1a1a";
|
||||
const VEHICLE_ICON_ID = "live-vehicle-icon";
|
||||
const ICON_IMAGE_SIZE = 48;
|
||||
const TRAIL_CHOICES = [0, 1, 2, 4, 8, 24];
|
||||
const DENM_COLOR = "#e63946";
|
||||
// ITS stations by ETSI station type (mcu-its-g5's decode.h names).
|
||||
const STATION_COLORS = {
|
||||
@@ -29,7 +28,6 @@ const STATION_COLORS = {
|
||||
pedestrian: "#7cc957",
|
||||
roadSideUnit: "#546619",
|
||||
};
|
||||
const LAYERS = ["live-its", "live-its-label", "live-vehicle-badge", "live-vehicle-icon", "live-vehicle-label"];
|
||||
|
||||
function ago(seconds) {
|
||||
if (seconds < 60) return `${seconds} s ago`;
|
||||
@@ -37,44 +35,161 @@ function ago(seconds) {
|
||||
return `${Math.round(seconds / 3600)} h ago`;
|
||||
}
|
||||
|
||||
// "passengerCar" → "passenger car"
|
||||
function stationLabel(station) {
|
||||
return String(station || "unknown").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
|
||||
}
|
||||
|
||||
export class LiveControl {
|
||||
function stored(key, fallback) {
|
||||
try {
|
||||
const value = localStorage.getItem(key);
|
||||
return value === null ? fallback : JSON.parse(value);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function store(key, value) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// private window / blocked storage: not remembered
|
||||
}
|
||||
}
|
||||
|
||||
function removeLayers(map, layers, sources) {
|
||||
for (const id of layers) if (map.getLayer(id)) map.removeLayer(id);
|
||||
for (const id of sources) if (map.getSource(id)) map.removeSource(id);
|
||||
}
|
||||
|
||||
function popupTable(title, rows) {
|
||||
return `<strong>${title}</strong><table class="live-popup">${rows
|
||||
.filter(Boolean)
|
||||
.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(String(v))}</td></tr>`)
|
||||
.join("")}</table>`;
|
||||
}
|
||||
|
||||
// One /api/live poll for every subscriber.
|
||||
const poller = {
|
||||
listeners: new Set(),
|
||||
timer: null,
|
||||
last: null,
|
||||
subscribe(fn) {
|
||||
this.listeners.add(fn);
|
||||
if (this.last) fn(this.last);
|
||||
if (this.listeners.size === 1) this.poll();
|
||||
},
|
||||
unsubscribe(fn) {
|
||||
this.listeners.delete(fn);
|
||||
if (!this.listeners.size) clearTimeout(this.timer);
|
||||
},
|
||||
async poll() {
|
||||
clearTimeout(this.timer);
|
||||
let data = null;
|
||||
try {
|
||||
const response = await fetch("/api/live");
|
||||
if (response.ok) data = await response.json();
|
||||
} catch {
|
||||
// network hiccup: listeners get null and say so
|
||||
}
|
||||
this.last = data;
|
||||
this.listeners.forEach((fn) => fn(data));
|
||||
if (this.listeners.size) this.timer = setTimeout(() => this.poll(), POLL_INTERVAL_MS);
|
||||
},
|
||||
refresh() {
|
||||
if (this.listeners.size) this.poll();
|
||||
},
|
||||
};
|
||||
|
||||
// --- Tracker -------------------------------------------------------------
|
||||
|
||||
const TRACKER_SOURCE = "live-tracker";
|
||||
const TRAIL_SOURCE = "live-tracker-trail";
|
||||
const TRACKER_LAYERS = ["live-tracker-trail", "live-tracker-badge", "live-tracker-icon", "live-tracker-label"];
|
||||
|
||||
export class TrackerControl {
|
||||
constructor(map) {
|
||||
this._map = map;
|
||||
this._enabled = false;
|
||||
this._data = null;
|
||||
this._timer = null;
|
||||
this._centered = false;
|
||||
// setStyle() (base map switch) drops custom sources/layers.
|
||||
this._onData = (data) => this._render(data);
|
||||
map.on("style.load", () => {
|
||||
if (this._enabled) this._addLayers().then(() => this._render());
|
||||
if (this._enabled) this._addLayers().then(() => this._render(this._data));
|
||||
});
|
||||
}
|
||||
|
||||
mount(li) {
|
||||
li.innerHTML = `
|
||||
<label>
|
||||
<div class="overlays-panel__row">
|
||||
<input type="checkbox" class="overlays-panel__toggle">
|
||||
<span class="overlays-panel__icon">${NPS_SYMBOLS.automobiles}</span>
|
||||
<span>Vehicle & ITS-G5</span>
|
||||
</label>
|
||||
<span class="overlays-panel__icon live-tracker__icon">${NPS_SYMBOLS.automobiles}</span>
|
||||
<button type="button" class="overlays-panel__name live-tracker__name" aria-expanded="false">Tracker</button>
|
||||
</div>
|
||||
<p class="live-panel__status" hidden></p>
|
||||
<div class="overlays-panel__details live-tracker__settings" hidden>
|
||||
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__card-toggle"> Info card on the map</label>
|
||||
<label class="live-tracker__row">Card opacity <input type="range" class="live-tracker__card-opacity" min="0.2" max="1" step="0.05"></label>
|
||||
<label class="live-tracker__row">Trail <select class="live-tracker__trail">${TRAIL_CHOICES.map((h) => `<option value="${h}">${h ? `last ${h} h` : "off"}</option>`).join("")}</select></label>
|
||||
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__logging"> Log positions (keeps the trail across restarts)</label>
|
||||
<input type="text" class="live-tracker__name-input" maxlength="40" placeholder="Name">
|
||||
<div class="live-tracker__style"></div>
|
||||
<button type="button" class="live-tracker__save">Save</button>
|
||||
</div>
|
||||
`;
|
||||
this._toggle = li.querySelector(".overlays-panel__toggle");
|
||||
this._iconEl = li.querySelector(".live-tracker__icon");
|
||||
this._nameButton = li.querySelector(".live-tracker__name");
|
||||
this._status = li.querySelector(".live-panel__status");
|
||||
this._settingsEl = li.querySelector(".live-tracker__settings");
|
||||
this._cardToggle = li.querySelector(".live-tracker__card-toggle");
|
||||
this._cardOpacity = li.querySelector(".live-tracker__card-opacity");
|
||||
this._trailSelect = li.querySelector(".live-tracker__trail");
|
||||
this._logging = li.querySelector(".live-tracker__logging");
|
||||
this._nameInput = li.querySelector(".live-tracker__name-input");
|
||||
this._style = new PointStyleFields(li.querySelector(".live-tracker__style"));
|
||||
|
||||
this._status.addEventListener("click", (event) => {
|
||||
if (event.target.closest(".live-panel__show")) this._showVehicle();
|
||||
if (event.target.closest(".live-panel__show")) this._showTracker();
|
||||
});
|
||||
if (!isLoggedIn()) {
|
||||
this._toggle.disabled = true;
|
||||
li.title = "Log in to see the car's live data";
|
||||
li.title = "Log in to see the tracker";
|
||||
return;
|
||||
}
|
||||
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
|
||||
this._nameButton.addEventListener("click", () => {
|
||||
const open = this._settingsEl.hidden;
|
||||
this._settingsEl.hidden = !open;
|
||||
this._nameButton.setAttribute("aria-expanded", String(open));
|
||||
});
|
||||
|
||||
// The card is per device (localStorage); the rest is the server's.
|
||||
this._cardToggle.checked = stored("trackerCard", true);
|
||||
this._cardOpacity.value = stored("trackerCardOpacity", 0.85);
|
||||
this._cardToggle.addEventListener("change", () => {
|
||||
store("trackerCard", this._cardToggle.checked);
|
||||
this._renderCard();
|
||||
});
|
||||
this._cardOpacity.addEventListener("input", () => {
|
||||
store("trackerCardOpacity", +this._cardOpacity.value);
|
||||
if (this._card) this._card.style.opacity = this._cardOpacity.value;
|
||||
});
|
||||
this._trailSelect.addEventListener("change", () => this._saveSettings({ trail_hours: this._trailSelect.value }));
|
||||
this._logging.addEventListener("change", () => this._saveSettings({ logging: this._logging.checked }));
|
||||
li.querySelector(".live-tracker__save").addEventListener("click", () =>
|
||||
this._saveSettings({ name: this._nameInput.value, icon: this._style.icon, color: this._style.color || "#1a1a1a" }),
|
||||
);
|
||||
}
|
||||
|
||||
async _saveSettings(changes) {
|
||||
const body = new URLSearchParams(Object.entries(changes).map(([k, v]) => [k, String(v)]));
|
||||
try {
|
||||
const response = await fetch("/api/live/settings", { method: "PUT", body });
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
poller.refresh();
|
||||
} catch {
|
||||
window.alert("Could not save the tracker settings.");
|
||||
}
|
||||
}
|
||||
|
||||
async _enable() {
|
||||
@@ -83,50 +198,239 @@ export class LiveControl {
|
||||
this._status.hidden = false;
|
||||
this._status.textContent = "Connecting…";
|
||||
await this._addLayers();
|
||||
this._poll();
|
||||
poller.subscribe(this._onData);
|
||||
}
|
||||
|
||||
_disable() {
|
||||
this._enabled = false;
|
||||
clearTimeout(this._timer);
|
||||
poller.unsubscribe(this._onData);
|
||||
this._status.hidden = true;
|
||||
for (const id of LAYERS) if (this._map.getLayer(id)) this._map.removeLayer(id);
|
||||
if (this._map.getSource(SOURCE_ID)) this._map.removeSource(SOURCE_ID);
|
||||
this._card?.remove();
|
||||
this._card = null;
|
||||
removeLayers(this._map, TRACKER_LAYERS, [TRACKER_SOURCE, TRAIL_SOURCE]);
|
||||
}
|
||||
|
||||
async _poll() {
|
||||
clearTimeout(this._timer);
|
||||
try {
|
||||
const response = await fetch("/api/live");
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
this._data = await response.json();
|
||||
this._render();
|
||||
// The first time the car shows up, go to it.
|
||||
if (!this._centered && this._data.vehicle) {
|
||||
this._centered = true;
|
||||
this._showVehicle();
|
||||
}
|
||||
} catch (err) {
|
||||
this._status.textContent = "Live data unavailable";
|
||||
}
|
||||
if (this._enabled) this._timer = setTimeout(() => this._poll(), POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
_showVehicle() {
|
||||
const vehicle = this._data?.vehicle;
|
||||
if (vehicle) this._map.flyTo({ center: [vehicle.longitude, vehicle.latitude], zoom: Math.max(this._map.getZoom(), 14) });
|
||||
_showTracker() {
|
||||
const t = this._data?.tracker;
|
||||
if (t) this._map.flyTo({ center: [t.longitude, t.latitude], zoom: Math.max(this._map.getZoom(), 14) });
|
||||
}
|
||||
|
||||
async _addLayers() {
|
||||
if (this._map.getSource(SOURCE_ID)) return;
|
||||
await this._registerImages();
|
||||
if (this._map.getSource(SOURCE_ID)) return; // a style.load raced this
|
||||
this._map.addSource(SOURCE_ID, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
|
||||
if (this._map.getSource(TRACKER_SOURCE)) return;
|
||||
const empty = { type: "FeatureCollection", features: [] };
|
||||
this._map.addSource(TRAIL_SOURCE, { type: "geojson", data: empty });
|
||||
this._map.addSource(TRACKER_SOURCE, { type: "geojson", data: empty });
|
||||
this._map.addLayer({
|
||||
id: "live-tracker-trail",
|
||||
type: "line",
|
||||
source: TRAIL_SOURCE,
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: { "line-color": ["get", "color"], "line-width": 3, "line-opacity": 0.75 },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-tracker-badge",
|
||||
type: "symbol",
|
||||
source: TRACKER_SOURCE,
|
||||
layout: { "icon-image": ["get", "badge"], "icon-size": 0.7, "icon-allow-overlap": true },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-tracker-icon",
|
||||
type: "symbol",
|
||||
source: TRACKER_SOURCE,
|
||||
layout: { "icon-image": ["get", "glyph"], "icon-size": 0.4, "icon-allow-overlap": true },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-tracker-label",
|
||||
type: "symbol",
|
||||
source: TRACKER_SOURCE,
|
||||
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 12, "text-offset": [0, 1.6], "text-anchor": "top", "text-allow-overlap": true },
|
||||
paint: { "text-color": "#1a1a1a", "text-halo-color": "#fff", "text-halo-width": 1.5 },
|
||||
});
|
||||
if (!this._interactive) {
|
||||
this._interactive = true;
|
||||
this._map.on("click", "live-tracker-badge", (event) => this._popup(event.lngLat));
|
||||
this._map.on("mouseenter", "live-tracker-badge", () => (this._map.getCanvas().style.cursor = "pointer"));
|
||||
this._map.on("mouseleave", "live-tracker-badge", () => (this._map.getCanvas().style.cursor = ""));
|
||||
}
|
||||
}
|
||||
|
||||
// The badge in the tracker's color and its icon in white, each image
|
||||
// registered once per color/icon.
|
||||
async _ensureImages(color, icon) {
|
||||
const badge = badgeImageId(color);
|
||||
if (!this._map.hasImage(badge)) {
|
||||
const image = await svgToImageData(MAP_MARKER_ICON.replace(/currentColor/g, color), ICON_IMAGE_SIZE);
|
||||
if (!this._map.hasImage(badge)) this._map.addImage(badge, image);
|
||||
}
|
||||
const glyph = `live-glyph-${icon}`;
|
||||
if (!this._map.hasImage(glyph)) {
|
||||
const svg = POI_ICONS[icon] || NPS_SYMBOLS.automobiles;
|
||||
const image = await svgToImageData(svg.replace(/currentColor/g, "#fff"), ICON_IMAGE_SIZE);
|
||||
if (!this._map.hasImage(glyph)) this._map.addImage(glyph, image);
|
||||
}
|
||||
return { badge, glyph };
|
||||
}
|
||||
|
||||
async _render(data) {
|
||||
if (!this._enabled) return;
|
||||
this._data = data;
|
||||
if (!data) {
|
||||
this._status.textContent = "Live data unavailable";
|
||||
return;
|
||||
}
|
||||
const settings = data.settings;
|
||||
this._applySettings(settings);
|
||||
if (!data.available) {
|
||||
this._status.textContent = "No MQTT broker configured on the server";
|
||||
return;
|
||||
}
|
||||
const t = data.tracker;
|
||||
this._status.innerHTML = t
|
||||
? `${escapeHtml(settings.name)} ${ago(t.age)} · <button type="button" class="live-panel__show">show</button>`
|
||||
: `No ${escapeHtml(settings.name)} position yet`;
|
||||
this._renderCard();
|
||||
if (!t) return;
|
||||
|
||||
const { badge, glyph } = await this._ensureImages(settings.color, settings.icon);
|
||||
this._map.getSource(TRACKER_SOURCE)?.setData({
|
||||
type: "FeatureCollection",
|
||||
features: [
|
||||
{
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [t.longitude, t.latitude] },
|
||||
properties: { badge, glyph, label: `${settings.name} · ${ago(t.age)}` },
|
||||
},
|
||||
],
|
||||
});
|
||||
const trail = [...(t.trail || []), [t.longitude, t.latitude]];
|
||||
this._map.getSource(TRAIL_SOURCE)?.setData({
|
||||
type: "FeatureCollection",
|
||||
features: trail.length > 1 ? [{ type: "Feature", geometry: { type: "LineString", coordinates: trail }, properties: { color: settings.color } }] : [],
|
||||
});
|
||||
if (!this._centered) {
|
||||
this._centered = true;
|
||||
this._showTracker();
|
||||
}
|
||||
}
|
||||
|
||||
// Server settings into the controls, unless the user is mid-edit there.
|
||||
_applySettings(settings) {
|
||||
const key = JSON.stringify(settings);
|
||||
if (key === this._settingsKey) return;
|
||||
this._settingsKey = key;
|
||||
this._nameButton.textContent = settings.name;
|
||||
this._iconEl.innerHTML = POI_ICONS[settings.icon] || NPS_SYMBOLS.automobiles;
|
||||
this._trailSelect.value = String(settings.trail_hours);
|
||||
this._logging.checked = settings.logging;
|
||||
if (document.activeElement !== this._nameInput) this._nameInput.value = settings.name;
|
||||
this._style.set(settings.icon, settings.color);
|
||||
}
|
||||
|
||||
// The floating info card (per-device on/off and opacity).
|
||||
_renderCard() {
|
||||
const t = this._data?.tracker;
|
||||
if (!this._enabled || !this._cardToggle.checked || !t) {
|
||||
this._card?.remove();
|
||||
this._card = null;
|
||||
return;
|
||||
}
|
||||
if (!this._card) {
|
||||
this._card = document.createElement("div");
|
||||
this._card.className = "live-tracker-card";
|
||||
this._card.addEventListener("click", () => this._showTracker());
|
||||
this._map.getContainer().appendChild(this._card);
|
||||
}
|
||||
this._card.style.opacity = this._cardOpacity.value;
|
||||
const s = this._data.settings;
|
||||
const battery = t.battery_level != null ? `${Math.round(t.battery_level)} %` : null;
|
||||
const rows = [
|
||||
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
|
||||
battery && ["Battery", `${battery}${t.usb_power ? " ⚡ charging" : ""}`],
|
||||
!battery && t.usb_power && ["Power", "⚡ USB"],
|
||||
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
|
||||
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
|
||||
["Updated", ago(t.age)],
|
||||
].filter(Boolean);
|
||||
this._card.innerHTML = `<div class="live-tracker-card__title"><span class="live-tracker-card__icon" style="background:${escapeHtml(s.color)}">${POI_ICONS[s.icon] || NPS_SYMBOLS.automobiles}</span>${escapeHtml(s.name)}</div>
|
||||
<table>${rows.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(v)}</td></tr>`).join("")}</table>`;
|
||||
}
|
||||
|
||||
_popup(lngLat) {
|
||||
const t = this._data?.tracker;
|
||||
if (!t) return;
|
||||
const html = popupTable(escapeHtml(this._data.settings.name), [
|
||||
["Position", `${(+t.latitude).toFixed(5)}, ${(+t.longitude).toFixed(5)}`],
|
||||
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
|
||||
t.course != null && ["Course", `${Math.round(t.course)}°`],
|
||||
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
|
||||
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
|
||||
t.battery_level != null && ["Battery", `${Math.round(t.battery_level)} %${t.usb_power ? " ⚡" : ""}`],
|
||||
["Updated", ago(t.age)],
|
||||
]);
|
||||
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
|
||||
}
|
||||
}
|
||||
|
||||
// --- ITS-G5 --------------------------------------------------------------
|
||||
|
||||
const ITS_SOURCE = "live-its";
|
||||
const ITS_LAYERS = ["live-its", "live-its-label"];
|
||||
|
||||
export class ItsControl {
|
||||
constructor(map) {
|
||||
this._map = map;
|
||||
this._enabled = false;
|
||||
this._data = null;
|
||||
this._onData = (data) => this._render(data);
|
||||
map.on("style.load", () => {
|
||||
if (this._enabled) {
|
||||
this._addLayers();
|
||||
this._render(this._data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
mount(li) {
|
||||
li.innerHTML = `
|
||||
<label>
|
||||
<input type="checkbox" class="overlays-panel__toggle">
|
||||
<span class="overlays-panel__icon">${NPS_SYMBOLS.radios}</span>
|
||||
<span>ITS-G5</span>
|
||||
</label>
|
||||
<p class="live-panel__status" hidden></p>
|
||||
`;
|
||||
this._toggle = li.querySelector(".overlays-panel__toggle");
|
||||
this._status = li.querySelector(".live-panel__status");
|
||||
if (!isLoggedIn()) {
|
||||
this._toggle.disabled = true;
|
||||
li.title = "Log in to see ITS-G5 stations";
|
||||
return;
|
||||
}
|
||||
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
|
||||
}
|
||||
|
||||
_enable() {
|
||||
this._enabled = true;
|
||||
this._status.hidden = false;
|
||||
this._status.textContent = "Connecting…";
|
||||
this._addLayers();
|
||||
poller.subscribe(this._onData);
|
||||
}
|
||||
|
||||
_disable() {
|
||||
this._enabled = false;
|
||||
poller.unsubscribe(this._onData);
|
||||
this._status.hidden = true;
|
||||
removeLayers(this._map, ITS_LAYERS, [ITS_SOURCE]);
|
||||
}
|
||||
|
||||
_addLayers() {
|
||||
if (this._map.getSource(ITS_SOURCE)) return;
|
||||
this._map.addSource(ITS_SOURCE, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
|
||||
this._map.addLayer({
|
||||
id: "live-its",
|
||||
type: "circle",
|
||||
source: SOURCE_ID,
|
||||
filter: ["==", ["get", "kind"], "its"],
|
||||
source: ITS_SOURCE,
|
||||
paint: {
|
||||
"circle-radius": ["case", ["==", ["get", "msg"], "DENM"], 8, 6],
|
||||
"circle-color": ["get", "color"],
|
||||
@@ -137,117 +441,54 @@ export class LiveControl {
|
||||
this._map.addLayer({
|
||||
id: "live-its-label",
|
||||
type: "symbol",
|
||||
source: SOURCE_ID,
|
||||
filter: ["==", ["get", "kind"], "its"],
|
||||
source: ITS_SOURCE,
|
||||
minzoom: 12,
|
||||
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 1.2], "text-anchor": "top" },
|
||||
paint: { "text-color": "#333", "text-halo-color": "#fff", "text-halo-width": 1.5 },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-vehicle-badge",
|
||||
type: "symbol",
|
||||
source: SOURCE_ID,
|
||||
filter: ["==", ["get", "kind"], "vehicle"],
|
||||
layout: { "icon-image": badgeImageId(VEHICLE_COLOR), "icon-size": 0.7, "icon-allow-overlap": true },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-vehicle-icon",
|
||||
type: "symbol",
|
||||
source: SOURCE_ID,
|
||||
filter: ["==", ["get", "kind"], "vehicle"],
|
||||
layout: { "icon-image": VEHICLE_ICON_ID, "icon-size": 0.4, "icon-allow-overlap": true },
|
||||
});
|
||||
this._map.addLayer({
|
||||
id: "live-vehicle-label",
|
||||
type: "symbol",
|
||||
source: SOURCE_ID,
|
||||
filter: ["==", ["get", "kind"], "vehicle"],
|
||||
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 12, "text-offset": [0, 1.6], "text-anchor": "top", "text-allow-overlap": true },
|
||||
paint: { "text-color": "#1a1a1a", "text-halo-color": "#fff", "text-halo-width": 1.5 },
|
||||
});
|
||||
if (!this._interactive) {
|
||||
this._interactive = true;
|
||||
for (const id of ["live-its", "live-vehicle-badge"]) {
|
||||
this._map.on("click", id, (event) => this._popup(event.features[0], event.lngLat));
|
||||
this._map.on("mouseenter", id, () => (this._map.getCanvas().style.cursor = "pointer"));
|
||||
this._map.on("mouseleave", id, () => (this._map.getCanvas().style.cursor = ""));
|
||||
}
|
||||
this._map.on("click", "live-its", (event) => this._popup(event.features[0].properties, event.lngLat));
|
||||
this._map.on("mouseenter", "live-its", () => (this._map.getCanvas().style.cursor = "pointer"));
|
||||
this._map.on("mouseleave", "live-its", () => (this._map.getCanvas().style.cursor = ""));
|
||||
}
|
||||
}
|
||||
|
||||
async _registerImages() {
|
||||
const badge = badgeImageId(VEHICLE_COLOR);
|
||||
if (!this._map.hasImage(badge)) {
|
||||
const image = await svgToImageData(MAP_MARKER_ICON.replace(/currentColor/g, VEHICLE_COLOR), ICON_IMAGE_SIZE);
|
||||
if (!this._map.hasImage(badge)) this._map.addImage(badge, image);
|
||||
_render(data) {
|
||||
if (!this._enabled) return;
|
||||
this._data = data;
|
||||
if (!data) {
|
||||
this._status.textContent = "Live data unavailable";
|
||||
return;
|
||||
}
|
||||
if (!this._map.hasImage(VEHICLE_ICON_ID)) {
|
||||
const image = await svgToImageData(NPS_SYMBOLS.automobiles.replace(/currentColor/g, "#fff"), ICON_IMAGE_SIZE);
|
||||
if (!this._map.hasImage(VEHICLE_ICON_ID)) this._map.addImage(VEHICLE_ICON_ID, image);
|
||||
}
|
||||
}
|
||||
|
||||
_render() {
|
||||
const data = this._data;
|
||||
if (!data) return;
|
||||
const features = [];
|
||||
const vehicle = data.vehicle;
|
||||
if (vehicle) {
|
||||
features.push({
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [vehicle.longitude, vehicle.latitude] },
|
||||
properties: { ...vehicle, kind: "vehicle", label: `Car · ${ago(vehicle.age)}` },
|
||||
});
|
||||
}
|
||||
for (const station of data.its || []) {
|
||||
features.push({
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [station.lon, station.lat] },
|
||||
properties: {
|
||||
...station,
|
||||
kind: "its",
|
||||
color: station.msg === "DENM" ? DENM_COLOR : STATION_COLORS[station.station] || "#888",
|
||||
label: `${station.msg} · ${stationLabel(station.station)}${station.speed > 1 ? ` · ${Math.round(station.speed)} km/h` : ""}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
this._map.getSource(SOURCE_ID)?.setData({ type: "FeatureCollection", features });
|
||||
|
||||
if (!data.available) {
|
||||
this._status.textContent = "No MQTT broker configured on the server";
|
||||
return;
|
||||
}
|
||||
const car = vehicle ? `Car ${ago(vehicle.age)} · <button type="button" class="live-panel__show">show</button>` : "No car position yet";
|
||||
const its = data.its?.length ? `${data.its.length} ITS-G5 station${data.its.length === 1 ? "" : "s"}` : "no ITS-G5 stations heard";
|
||||
this._status.innerHTML = `${car} · ${its}`;
|
||||
const stations = data.its || [];
|
||||
this._status.textContent = stations.length ? `${stations.length} station${stations.length === 1 ? "" : "s"} heard` : "No stations heard";
|
||||
this._map.getSource(ITS_SOURCE)?.setData({
|
||||
type: "FeatureCollection",
|
||||
features: stations.map((station) => ({
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [station.lon, station.lat] },
|
||||
properties: {
|
||||
...station,
|
||||
color: station.msg === "DENM" ? DENM_COLOR : STATION_COLORS[station.station] || "#888",
|
||||
label: `${station.msg} · ${stationLabel(station.station)}${station.speed > 1 ? ` · ${Math.round(station.speed)} km/h` : ""}`,
|
||||
},
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
_popup(feature, lngLat) {
|
||||
const p = feature.properties;
|
||||
const rows =
|
||||
p.kind === "vehicle"
|
||||
? [
|
||||
["Position", `${(+p.latitude).toFixed(5)}, ${(+p.longitude).toFixed(5)}`],
|
||||
p.speed != null && ["Speed", `${Math.round(p.speed)} km/h`],
|
||||
p.course != null && ["Course", `${Math.round(p.course)}°`],
|
||||
p.altitude != null && ["Altitude", `${Math.round(p.altitude)} m`],
|
||||
p.gps_accuracy != null && ["Accuracy", `±${p.gps_accuracy} m`],
|
||||
p.battery_level != null && ["Battery", `${Math.round(p.battery_level)} %`],
|
||||
["Updated", ago(p.age)],
|
||||
]
|
||||
: [
|
||||
["Message", p.msg],
|
||||
["Station", stationLabel(p.station)],
|
||||
["Speed", `${Math.round(p.speed)} km/h`],
|
||||
["Heading", `${Math.round(p.heading)}°`],
|
||||
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
|
||||
["Heard", ago(p.age)],
|
||||
];
|
||||
const title = p.kind === "vehicle" ? "Car" : `ITS-G5 ${escapeHtml(p.msg)}`;
|
||||
const html = `<strong>${title}</strong><table class="live-popup">${rows
|
||||
.filter(Boolean)
|
||||
.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(String(v))}</td></tr>`)
|
||||
.join("")}</table>`;
|
||||
_popup(p, lngLat) {
|
||||
const html = popupTable(`ITS-G5 ${escapeHtml(p.msg)}`, [
|
||||
["Station", stationLabel(p.station)],
|
||||
["Speed", `${Math.round(p.speed)} km/h`],
|
||||
["Heading", `${Math.round(p.heading)}°`],
|
||||
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
|
||||
["Heard", ago(p.age)],
|
||||
]);
|
||||
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
|
||||
}
|
||||
}
|
||||
+23
-21
@@ -6,7 +6,7 @@ import { RadarControl } from "/js/radar.js";
|
||||
import { ShadowControl } from "/js/shadow.js";
|
||||
import { ContourControl } from "/js/contour.js";
|
||||
import { HikingTrailsControl } from "/js/hiking_trails.js";
|
||||
import { LiveControl } from "/js/live.js";
|
||||
import { TrackerControl, ItsControl } from "/js/live.js";
|
||||
import { NpsControl } from "/js/nps.js";
|
||||
|
||||
const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||
@@ -188,7 +188,8 @@ export class OverlaysControl {
|
||||
this._shadow = new ShadowControl(map);
|
||||
this._contour = new ContourControl(map);
|
||||
this._hikingTrails = new HikingTrailsControl(map);
|
||||
this._live = new LiveControl(map);
|
||||
this._tracker = new TrackerControl(map);
|
||||
this._its = new ItsControl(map);
|
||||
this._nps = new NpsControl(map);
|
||||
this._wikiEnabled = false; // the checkbox's own state
|
||||
this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled
|
||||
@@ -216,26 +217,27 @@ export class OverlaysControl {
|
||||
.querySelector(".basemap-panel__close")
|
||||
.addEventListener("click", () => this._togglePanel(false));
|
||||
|
||||
// Items grouped under a heading each; [heading, [[mount, expandable]]].
|
||||
const groups = [
|
||||
["Terrain", [[(li) => this._hillshade.mount(li)], [(li) => this._shadow.mount(li), true], [(li) => this._contour.mount(li)]]],
|
||||
["Weather", [[(li) => this._radar.mount(li), true]]],
|
||||
["Places & trails", [[(li) => this._hikingTrails.mount(li), true], [(li) => this._mountWiki(li)], [(li) => this._nps.mount(li)]]],
|
||||
["Live", [[(li) => this._tracker.mount(li)], [(li) => this._its.mount(li)]]],
|
||||
];
|
||||
const list = this._panel.querySelector(".overlays-panel__list");
|
||||
list.innerHTML = `
|
||||
<li class="overlays-panel__item"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
`;
|
||||
const [hillshadeItem, wikiItem, radarItem, shadowItem, contourItem, hikingTrailsItem, liveItem, npsItem] = list.children;
|
||||
this._hillshade.mount(hillshadeItem);
|
||||
this._mountWiki(wikiItem);
|
||||
this._radar.mount(radarItem);
|
||||
this._shadow.mount(shadowItem);
|
||||
this._contour.mount(contourItem);
|
||||
this._hikingTrails.mount(hikingTrailsItem);
|
||||
this._live.mount(liveItem);
|
||||
this._nps.mount(npsItem);
|
||||
list.innerHTML = "";
|
||||
for (const [heading, items] of groups) {
|
||||
const head = document.createElement("li");
|
||||
head.className = "overlays-panel__group";
|
||||
head.textContent = heading;
|
||||
list.appendChild(head);
|
||||
for (const [mount, expandable] of items) {
|
||||
const li = document.createElement("li");
|
||||
li.className = `overlays-panel__item${expandable ? " overlays-panel__item--expandable" : ""}`;
|
||||
list.appendChild(li);
|
||||
mount(li);
|
||||
}
|
||||
}
|
||||
|
||||
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
|
||||
|
||||
|
||||
Reference in new issue
Block a user