Add files via upload
This commit is contained in:
1 parent
055077803c
commit
63da9cdbba
7 files changed
+1046
-612
No files matched your search
@@ -1,88 +1,142 @@
|
||||
// Schlanker Wrapper um alle Aufrufe an das ÖPNV-Navi-Backend.
|
||||
// Wirft bei Fehlern verständliche Errors, die die UI direkt anzeigen kann.
|
||||
|
||||
const API = (() => {
|
||||
const BASE = window.APP_CONFIG.API_BASE;
|
||||
|
||||
async function request(path) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`);
|
||||
} catch (networkErr) {
|
||||
throw new Error('Backend nicht erreichbar. Prüfe deine Internetverbindung.');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `Fehler ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body.error) message = body.error;
|
||||
} catch (_) {
|
||||
// Antwort war kein JSON, Standardmeldung behalten
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function qs(params) {
|
||||
const parts = [];
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
|
||||
});
|
||||
return parts.join('&');
|
||||
}
|
||||
|
||||
return {
|
||||
searchLocations(query) {
|
||||
return request(`/locations/search?query=${encodeURIComponent(query)}`);
|
||||
},
|
||||
|
||||
nearby({ lat, lon, distance, results, includePoi }) {
|
||||
return request(`/locations/nearby?${qs({ lat, lon, distance, results, includePoi })}`);
|
||||
},
|
||||
|
||||
getDepartures(stationId, { duration = 30, results = 15, modes } = {}) {
|
||||
return request(`/departures/${encodeURIComponent(stationId)}?${qs({ duration, results, modes })}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* `from`/`to` sind entweder { id, name } (Haltestelle) oder
|
||||
* { lat, lon, name } (Adresse/POI/GPS-Standort, wird als Adresse behandelt).
|
||||
*/
|
||||
getJourneys({ from, to, when, arrival, modes, polylines, results = 5 }) {
|
||||
const fromParams = from.id
|
||||
? { fromId: from.id }
|
||||
: { fromLat: from.lat, fromLon: from.lon, fromAddress: from.name };
|
||||
const toParams = to.id
|
||||
? { toId: to.id }
|
||||
: { toLat: to.lat, toLon: to.lon, toAddress: to.name };
|
||||
|
||||
return request(
|
||||
`/journeys?${qs({
|
||||
...fromParams,
|
||||
...toParams,
|
||||
when: when || undefined,
|
||||
arrival: arrival ? 'true' : undefined,
|
||||
modes,
|
||||
polylines: polylines ? 'true' : undefined,
|
||||
results,
|
||||
})}`,
|
||||
);
|
||||
},
|
||||
|
||||
getTrip(tripId, { polyline = false } = {}) {
|
||||
return request(`/trip/${encodeURIComponent(tripId)}?${qs({ polyline: polyline ? 'true' : undefined })}`);
|
||||
},
|
||||
|
||||
getRemarks({ modes, results = 30 } = {}) {
|
||||
return request(`/remarks?${qs({ modes, results })}`);
|
||||
},
|
||||
|
||||
getRadar({ north, west, south, east, modes, tripId }) {
|
||||
return request(`/radar?${qs({ north, west, south, east, modes, tripId })}`);
|
||||
},
|
||||
};
|
||||
// Schlanker Wrapper um alle Aufrufe an das ÖPNV-Navi-Backend.
|
||||
// Wirft bei Fehlern verständliche Errors, die die UI direkt anzeigen kann.
|
||||
|
||||
const API = (() => {
|
||||
const BASE = window.APP_CONFIG.API_BASE;
|
||||
|
||||
async function request(path, options = {}) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, options);
|
||||
} catch (networkErr) {
|
||||
throw new Error('Backend nicht erreichbar. Prüfe deine Internetverbindung.');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `Fehler ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body.error) message = body.error;
|
||||
} catch (_) {
|
||||
// Antwort war kein JSON, Standardmeldung behalten
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function postJson(path, body) {
|
||||
return request(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
// Baut einen Query-String und lässt dabei undefined/null-Werte weg.
|
||||
function qs(params) {
|
||||
const parts = [];
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
|
||||
});
|
||||
return parts.join('&');
|
||||
}
|
||||
|
||||
return {
|
||||
searchLocations(query) {
|
||||
return request(`/locations/search?query=${encodeURIComponent(query)}`);
|
||||
},
|
||||
|
||||
// Bundesweite DB-IRIS-Anbindung: nur "echte" DB-Bahnhöfe (Fernverkehr +
|
||||
// viele Regio-Stationen), OHNE U-Bahn/Tram/Bus - siehe searchAll().
|
||||
searchDbStations(query) {
|
||||
return request(`/db/stations/search?query=${encodeURIComponent(query)}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* Kombinierte Suche: fragt VBB (U-Bahn/S-Bahn/Tram/Bus, primär Berlin/
|
||||
* Brandenburg) UND die bundesweite DB-Anbindung (nur echte Bahnhöfe)
|
||||
* parallel ab und liefert eine gemeinsame, quellenmarkierte Liste zurück.
|
||||
* So funktioniert Nahverkehr weiterhin lokal, und man bekommt zusätzlich
|
||||
* bundesweite Fernverkehrs-/Regio-Bahnhöfe.
|
||||
*/
|
||||
async searchAll(query) {
|
||||
const [vbbResult, dbResult] = await Promise.allSettled([
|
||||
this.searchLocations(query),
|
||||
this.searchDbStations(query),
|
||||
]);
|
||||
|
||||
const vbbStations = vbbResult.status === 'fulfilled'
|
||||
? vbbResult.value.locations
|
||||
.filter((l) => l.kind === 'stop')
|
||||
.map((l) => ({ id: l.id, name: l.name, source: 'vbb' }))
|
||||
: [];
|
||||
|
||||
const dbStations = dbResult.status === 'fulfilled'
|
||||
? dbResult.value.stations.map((s) => ({ id: s.evaNumber, name: s.name, source: 'db' }))
|
||||
: [];
|
||||
|
||||
return [...vbbStations, ...dbStations];
|
||||
},
|
||||
|
||||
getDbDepartures(evaNumber, { hours = 2, results = 20 } = {}) {
|
||||
return request(`/db/departures/${encodeURIComponent(evaNumber)}?${qs({ hours, results })}`);
|
||||
},
|
||||
|
||||
nearby({ lat, lon, distance, results, includePoi }) {
|
||||
return request(`/locations/nearby?${qs({ lat, lon, distance, results, includePoi })}`);
|
||||
},
|
||||
|
||||
getDepartures(stationId, { duration = 30, results = 15, modes } = {}) {
|
||||
return request(`/departures/${encodeURIComponent(stationId)}?${qs({ duration, results, modes })}`);
|
||||
},
|
||||
|
||||
/**
|
||||
* Nutzt unsere selbst gehostete OTP2-Instanz (VBB-Region) statt HAFAS.
|
||||
* `from`/`to` brauchen nur noch { lat, lon, name } - egal ob Haltestelle,
|
||||
* Adresse, POI oder GPS-Standort, alle liefern das bereits mit.
|
||||
*/
|
||||
getJourneys({ from, to, when, arrival, polylines, results = 5 }) {
|
||||
return request(
|
||||
`/otp/journeys?${qs({
|
||||
fromLat: from.lat,
|
||||
fromLon: from.lon,
|
||||
toLat: to.lat,
|
||||
toLon: to.lon,
|
||||
when: when || undefined,
|
||||
arrival: arrival ? 'true' : undefined,
|
||||
polylines: polylines ? 'true' : undefined,
|
||||
results,
|
||||
})}`,
|
||||
);
|
||||
},
|
||||
|
||||
getFares() {
|
||||
return request('/fares');
|
||||
},
|
||||
|
||||
getNearbyDisruptions({ lat, lon, distance, stops }) {
|
||||
return request(`/disruptions/nearby?${qs({ lat, lon, distance, stops })}`);
|
||||
},
|
||||
|
||||
getTrip(tripId, { polyline = false } = {}) {
|
||||
return request(`/trip/${encodeURIComponent(tripId)}?${qs({ polyline: polyline ? 'true' : undefined })}`);
|
||||
},
|
||||
|
||||
getRemarks({ modes, results = 30 } = {}) {
|
||||
return request(`/remarks?${qs({ modes, results })}`);
|
||||
},
|
||||
|
||||
getRadar({ north, west, south, east, modes, tripId }) {
|
||||
return request(`/radar?${qs({ north, west, south, east, modes, tripId })}`);
|
||||
},
|
||||
|
||||
// Nächste Abfahrt für mehrere Haltestellen gleichzeitig (z.B. für die
|
||||
// Favoriten-Übersicht auf der Startseite) - eine Anfrage statt N.
|
||||
getSummaryDepartures(stations) {
|
||||
return postJson('/summary/departures', { stations });
|
||||
},
|
||||
};
|
||||
})();
|
||||
@@ -1,12 +1,11 @@
|
||||
const App = (() => {
|
||||
const FAVORITES_KEY = 'oepnv-navi:favorites';
|
||||
const LAST_STOP_KEY = 'oepnv-navi:last-stop';
|
||||
const RECENT_SEARCHES_KEY = 'oepnv-navi:recent-searches';
|
||||
const FAVORITES_KEY = 'oepnv-navi:db-favorites';
|
||||
const LAST_STOP_KEY = 'oepnv-navi:db-last-stop';
|
||||
const RECENT_SEARCHES_KEY = 'oepnv-navi:db-recent-searches';
|
||||
|
||||
let currentStop = null;
|
||||
let departuresPollHandle = null;
|
||||
let departuresModeFilter = null;
|
||||
let journeyModeFilter = null;
|
||||
|
||||
let journeyFrom = null;
|
||||
let journeyTo = null;
|
||||
@@ -38,7 +37,7 @@ const App = (() => {
|
||||
function saveRecentSearch(station) {
|
||||
if (!station || !station.name) return;
|
||||
const items = loadRecentSearches().filter((item) => item.id !== station.id);
|
||||
items.unshift({ id: station.id, name: station.name, latitude: station.latitude, longitude: station.longitude });
|
||||
items.unshift({ id: station.id, name: station.name, source: station.source });
|
||||
localStorage.setItem(RECENT_SEARCHES_KEY, JSON.stringify(items.slice(0, 6)));
|
||||
renderRecentSearches();
|
||||
}
|
||||
@@ -97,7 +96,15 @@ const App = (() => {
|
||||
if (cardContainer) {
|
||||
const card = document.createElement('button');
|
||||
card.className = 'favorite-card';
|
||||
card.innerHTML = `<span class="favorite-card__star">★</span><span><strong>${escapeHtml(fav.name)}</strong><small>Abfahrten anzeigen</small></span><span class="favorite-card__arrow">→</span>`;
|
||||
card.dataset.favId = fav.id;
|
||||
card.innerHTML = `
|
||||
<span class="favorite-card__star">★</span>
|
||||
<span>
|
||||
<strong>${escapeHtml(fav.name)}</strong>
|
||||
<small class="favorite-card__next" data-next-departure>Lade nächste Abfahrt…</small>
|
||||
</span>
|
||||
<span class="favorite-card__arrow">→</span>
|
||||
`;
|
||||
card.addEventListener('click', () => selectStation(fav));
|
||||
cardContainer.appendChild(card);
|
||||
}
|
||||
@@ -107,6 +114,38 @@ const App = (() => {
|
||||
if (empty) empty.hidden = favorites.length > 0;
|
||||
const home = document.getElementById('favorites-home');
|
||||
if (home) home.hidden = favorites.length === 0;
|
||||
|
||||
if (favorites.length > 0) loadFavoriteNextDepartures(favorites);
|
||||
}
|
||||
|
||||
async function loadFavoriteNextDepartures(favorites) {
|
||||
const stations = favorites.map((f) => ({ id: f.id, source: f.source || 'vbb', name: f.name }));
|
||||
try {
|
||||
const { results } = await API.getSummaryDepartures(stations);
|
||||
results.forEach((r) => {
|
||||
const card = document.querySelector(`.favorite-card[data-fav-id="${CSS.escape(String(r.id))}"]`);
|
||||
if (!card) return;
|
||||
const el = card.querySelector('[data-next-departure]');
|
||||
if (!el) return;
|
||||
|
||||
if (r.error || !r.nextDeparture) {
|
||||
el.textContent = 'Keine Abfahrt gefunden';
|
||||
return;
|
||||
}
|
||||
|
||||
const dep = r.nextDeparture;
|
||||
const minutesUntil = dep.when ? Math.max(0, Math.round((new Date(dep.when) - new Date()) / 60000)) : null;
|
||||
if (dep.cancelled) {
|
||||
el.innerHTML = `<span class="favorite-card__cancelled">${escapeHtml(dep.line || '')} fällt aus</span>`;
|
||||
} else {
|
||||
el.textContent = `${dep.line || '?'} → ${dep.direction || ''} · ${minutesUntil != null ? minutesUntil + ' min' : ''}`;
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
// Stillschweigend ignorieren - die Karten zeigen dann weiterhin "Lade..."
|
||||
// bzw. der Nutzer bekommt die Abfahrten trotzdem beim Antippen der Karte.
|
||||
console.error('Sammel-Abfahrten-Fehler:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFavoriteButton() {
|
||||
@@ -155,9 +194,8 @@ const App = (() => {
|
||||
|
||||
searchDebounce = setTimeout(async () => {
|
||||
try {
|
||||
const { locations } = await API.searchLocations(query);
|
||||
const stops = locations.filter((l) => l.kind === 'stop');
|
||||
renderSearchResults(results, stops, (station) => {
|
||||
const stations = await API.searchAll(query);
|
||||
renderSearchResults(results, stations, (station) => {
|
||||
selectStation(station);
|
||||
input.value = '';
|
||||
results.hidden = true;
|
||||
@@ -178,10 +216,13 @@ const App = (() => {
|
||||
});
|
||||
}
|
||||
|
||||
function kindIcon(kind) {
|
||||
if (kind === 'address') return '📍';
|
||||
if (kind === 'poi') return '⭐';
|
||||
return '🚏';
|
||||
// Ein Symbol pro Ergebnis-Herkunft: VBB-Haltestelle (Nahverkehr), echter
|
||||
// DB-Bahnhof (bundesweit), oder Adresse/POI (nur im Routenplaner relevant).
|
||||
function resultIcon(loc) {
|
||||
if (loc.source === 'db') return '🚉';
|
||||
if (loc.kind === 'address') return '📍';
|
||||
if (loc.kind === 'poi') return '⭐';
|
||||
return '🚏'; // VBB-Haltestelle (U/S/Tram/Bus)
|
||||
}
|
||||
|
||||
function renderSearchResults(container, locations, onSelect) {
|
||||
@@ -196,7 +237,8 @@ const App = (() => {
|
||||
locations.forEach((loc) => {
|
||||
const li = document.createElement('li');
|
||||
li.className = 'search-result';
|
||||
li.innerHTML = `<span class="search-result__icon">${kindIcon(loc.kind)}</span> ${loc.name}`;
|
||||
const badge = loc.source === 'db' ? '<span class="search-result__badge">DB · bundesweit</span>' : '';
|
||||
li.innerHTML = `<span class="search-result__icon">${resultIcon(loc)}</span> ${loc.name}${badge}`;
|
||||
li.addEventListener('click', () => onSelect(loc));
|
||||
container.appendChild(li);
|
||||
});
|
||||
@@ -206,7 +248,7 @@ const App = (() => {
|
||||
|
||||
function selectStation(station) {
|
||||
currentStop = station;
|
||||
localStorage.setItem(LAST_STOP_KEY, JSON.stringify({ id: station.id, name: station.name }));
|
||||
localStorage.setItem(LAST_STOP_KEY, JSON.stringify({ id: station.id, name: station.name, source: station.source }));
|
||||
saveRecentSearch(station);
|
||||
activateTab('departures');
|
||||
document.getElementById('board-station-name').textContent = station.name;
|
||||
@@ -214,6 +256,12 @@ const App = (() => {
|
||||
document.getElementById('welcome-panel').hidden = true;
|
||||
document.getElementById('departures-view').hidden = false;
|
||||
updateFavoriteButton();
|
||||
|
||||
// Der Modefilter (Verkehrsmittel S/U/Tram/Bus/...) gilt nur für VBB-
|
||||
// Haltestellen - die bundesweite DB-Anbindung unterstützt keine Filterung.
|
||||
const modeFilterEl = document.getElementById('departures-mode-filter');
|
||||
if (modeFilterEl) modeFilterEl.hidden = station.source === 'db';
|
||||
|
||||
loadDepartures();
|
||||
restartDeparturesPolling();
|
||||
}
|
||||
@@ -223,28 +271,39 @@ const App = (() => {
|
||||
const board = document.getElementById('departure-board');
|
||||
|
||||
try {
|
||||
const { departures } = await API.getDepartures(currentStop.id, {
|
||||
modes: departuresModeFilter ? departuresModeFilter.getModesParam() : null,
|
||||
});
|
||||
const departures = currentStop.source === 'db'
|
||||
? (await API.getDbDepartures(currentStop.id)).departures
|
||||
: (await API.getDepartures(currentStop.id, {
|
||||
modes: departuresModeFilter ? departuresModeFilter.getModesParam() : null,
|
||||
})).departures;
|
||||
renderDepartureBoard(departures);
|
||||
} catch (err) {
|
||||
board.innerHTML = `<div class="board-error">⚠ ${err.message}</div>`;
|
||||
}
|
||||
}
|
||||
function renderDepartureBoard(departures) {
|
||||
|
||||
let lastRenderedSource = null;
|
||||
|
||||
function renderDepartureBoard(departures) {
|
||||
const board = document.getElementById('departure-board');
|
||||
const source = currentStop ? currentStop.source : null;
|
||||
|
||||
if (departures.length === 0) {
|
||||
board.innerHTML = '<div class="board-empty">Keine Abfahrten für die gewählten Verkehrsmittel in den nächsten 30 Minuten.</div>';
|
||||
lastRenderedSource = source;
|
||||
return;
|
||||
}
|
||||
|
||||
const existingRows = board.querySelectorAll('.flap-row');
|
||||
if (existingRows.length !== departures.length) {
|
||||
// Board komplett neu aufbauen, wenn sich die Anzahl ändert ODER die
|
||||
// Quelle wechselt (VBB<->DB) - sonst blieben bei zufällig gleicher
|
||||
// Zeilenzahl alte Klick-Handler/Klassen vom vorherigen Backend hängen.
|
||||
if (existingRows.length !== departures.length || lastRenderedSource !== source) {
|
||||
board.innerHTML = '';
|
||||
departures.forEach((dep, i) => {
|
||||
board.appendChild(buildDepartureRow(dep, i));
|
||||
});
|
||||
lastRenderedSource = source;
|
||||
}
|
||||
|
||||
departures.forEach((dep, i) => {
|
||||
@@ -256,8 +315,6 @@ const App = (() => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'flap-row';
|
||||
row.style.setProperty('--row-index', index);
|
||||
row.setAttribute('role', 'button');
|
||||
row.setAttribute('tabindex', '0');
|
||||
row.innerHTML = `
|
||||
<div class="flap-field flap-field--line">
|
||||
<span class="flap-label">Linie</span>
|
||||
@@ -276,16 +333,25 @@ const App = (() => {
|
||||
<span class="flap-cell flap-cell--time" data-field="time"></span>
|
||||
</div>
|
||||
`;
|
||||
const openModal = () => {
|
||||
if (row.dataset.tripId) TripModal.open(row.dataset.tripId);
|
||||
};
|
||||
row.addEventListener('click', openModal);
|
||||
row.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
openModal();
|
||||
}
|
||||
});
|
||||
|
||||
// Klick-für-Fahrt-Details gibt es aktuell nur für VBB-Haltestellen (kein
|
||||
// passender Backend-Endpunkt für DB-Streckenverlauf/Zwischenhalte).
|
||||
if (currentStop && currentStop.source !== 'db') {
|
||||
row.setAttribute('role', 'button');
|
||||
row.setAttribute('tabindex', '0');
|
||||
row.classList.add('flap-row--clickable');
|
||||
const openModal = () => {
|
||||
if (row.dataset.tripId) TripModal.open(row.dataset.tripId);
|
||||
};
|
||||
row.addEventListener('click', openModal);
|
||||
row.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
openModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
@@ -361,6 +427,10 @@ const App = (() => {
|
||||
if (tabName === 'disruptions' && !remarksLoadedOnce) {
|
||||
loadRemarks();
|
||||
}
|
||||
|
||||
if (tabName === 'fares' && !faresLoadedOnce) {
|
||||
loadFares();
|
||||
}
|
||||
}
|
||||
|
||||
function initNearby() {
|
||||
@@ -433,6 +503,78 @@ const App = (() => {
|
||||
});
|
||||
}
|
||||
|
||||
function initNearbyDisruptions() {
|
||||
const btn = document.getElementById('disruptions-locate');
|
||||
if (!btn) return;
|
||||
btn.addEventListener('click', async () => {
|
||||
const container = document.getElementById('nearby-disruptions-list');
|
||||
container.innerHTML = '<div class="board-empty">Standort wird ermittelt…</div>';
|
||||
try {
|
||||
const { lat, lon } = await getUserLocation();
|
||||
container.innerHTML = '<div class="board-empty">Suche Störungen in der Nähe…</div>';
|
||||
const { disruptions } = await API.getNearbyDisruptions({ lat, lon, distance: 1000, stops: 6 });
|
||||
renderNearbyDisruptions(disruptions, container);
|
||||
} catch (err) {
|
||||
container.innerHTML = `<div class="board-error">⚠ ${err.message}</div>`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function renderNearbyDisruptions(disruptions, container) {
|
||||
container.innerHTML = '';
|
||||
if (disruptions.length === 0) {
|
||||
container.innerHTML = '<div class="board-empty">Aktuell keine Störungen in deiner Nähe bekannt.</div>';
|
||||
return;
|
||||
}
|
||||
disruptions.forEach((d) => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'remark-card';
|
||||
const lines = d.affectedLines.length ? `Linie${d.affectedLines.length > 1 ? 'n' : ''} ${d.affectedLines.join(', ')}` : '';
|
||||
const stops = d.affectedStops.length ? ` · nahe ${d.affectedStops.join(', ')}` : '';
|
||||
card.innerHTML = `
|
||||
<div class="remark-card__summary">⚠ ${escapeHtml(d.summary || 'Hinweis')}</div>
|
||||
<div class="remark-card__text">${escapeHtml(d.text || '')}</div>
|
||||
<div class="remark-card__meta">${escapeHtml(lines)}${escapeHtml(stops)}</div>
|
||||
`;
|
||||
container.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
let faresLoadedOnce = false;
|
||||
|
||||
async function loadFares() {
|
||||
const content = document.getElementById('fares-content');
|
||||
const companies = document.getElementById('fares-companies');
|
||||
try {
|
||||
const fares = await API.getFares();
|
||||
faresLoadedOnce = true;
|
||||
document.getElementById('fares-stand').textContent = `Stand: ${new Date(fares.stand).toLocaleDateString('de-DE')}`;
|
||||
|
||||
content.innerHTML = fares.gruppen.map((gruppe) => `
|
||||
<div class="fare-group">
|
||||
<h3>${escapeHtml(gruppe.titel)}</h3>
|
||||
<div class="fare-rows">
|
||||
${gruppe.tickets.map((t) => `
|
||||
<div class="fare-row">
|
||||
<div><strong>${escapeHtml(t.name)}</strong><small>${escapeHtml(t.bereich)}${t.hinweis ? ' · ' + escapeHtml(t.hinweis) : ''}</small></div>
|
||||
<div class="fare-row__price">${t.preis.toFixed(2).replace('.', ',')} €</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
companies.innerHTML = fares.unternehmen.map((u) => `
|
||||
<a class="company-link" href="${u.url}" target="_blank" rel="noopener noreferrer">
|
||||
<span><strong>${escapeHtml(u.name)}</strong><small>${escapeHtml(u.beschreibung)}</small></span>
|
||||
<span class="company-link__arrow">↗</span>
|
||||
</a>
|
||||
`).join('');
|
||||
} catch (err) {
|
||||
content.innerHTML = `<div class="board-error">⚠ ${err.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRemarks() {
|
||||
const container = document.getElementById('remarks-list');
|
||||
container.innerHTML = '<div class="board-empty">Lade Störungsmeldungen…</div>';
|
||||
@@ -465,6 +607,7 @@ const App = (() => {
|
||||
container.appendChild(card);
|
||||
});
|
||||
}
|
||||
|
||||
function initJourneyPlanner() {
|
||||
setupJourneyInput('journey-from', (loc) => (journeyFrom = loc));
|
||||
setupJourneyInput('journey-to', (loc) => (journeyTo = loc));
|
||||
@@ -514,7 +657,6 @@ const App = (() => {
|
||||
to: journeyTo,
|
||||
when: whenInput || undefined,
|
||||
arrival: journeyArrivalMode,
|
||||
modes: journeyModeFilter ? journeyModeFilter.getModesParam() : null,
|
||||
results: 5,
|
||||
};
|
||||
lastJourneyParams = params;
|
||||
@@ -544,7 +686,7 @@ const App = (() => {
|
||||
try {
|
||||
const { locations } = await API.searchLocations(query);
|
||||
renderSearchResults(results, locations, (loc) => {
|
||||
onSelect({ id: loc.id || undefined, lat: loc.latitude, lon: loc.longitude, name: loc.name });
|
||||
onSelect({ id: loc.id || undefined, lat: loc.latitude, lon: loc.longitude, name: loc.name, kind: loc.kind });
|
||||
input.value = loc.name;
|
||||
results.hidden = true;
|
||||
});
|
||||
@@ -599,8 +741,15 @@ const App = (() => {
|
||||
})
|
||||
.join('');
|
||||
|
||||
const fareHtml = journey.fareEstimate && journey.fareEstimate.price != null
|
||||
? journey.fareEstimate.exact
|
||||
? `<div class="journey-fare journey-fare--exact">💶 ${journey.fareEstimate.price.toFixed(2).replace('.', ',')} € <small>(Tarifbereich ${journey.fareEstimate.zone}, Einzelfahrschein, ohne Gewähr)</small></div>`
|
||||
: `<div class="journey-fare">💶 ca. ${journey.fareEstimate.price.toFixed(2).replace('.', ',')} € <small>(Tarifbereich ~${journey.fareEstimate.zone}, geschätzt, ohne Gewähr)</small></div>`
|
||||
: '';
|
||||
|
||||
card.innerHTML = `
|
||||
${legsHtml}
|
||||
${fareHtml}
|
||||
<button class="journey-map-toggle" data-journey-index="${journeyIndex}">🗺️ Streckenverlauf anzeigen</button>
|
||||
<div class="journey-mini-map" id="journey-mini-map-${journeyIndex}"></div>
|
||||
`;
|
||||
@@ -664,7 +813,7 @@ const App = (() => {
|
||||
|
||||
setTimeout(() => {
|
||||
miniMapInstance = LiveMap.createMiniMap(mapEl.id, journeyWithPolylines);
|
||||
}, 200);
|
||||
}, 200); // Wartet auf CSS-Höhen-Transition, damit Leaflet die Größe korrekt berechnet
|
||||
}
|
||||
|
||||
function restoreLastStop() {
|
||||
@@ -681,6 +830,7 @@ const App = (() => {
|
||||
initTabs();
|
||||
initJourneyPlanner();
|
||||
initNearby();
|
||||
initNearbyDisruptions();
|
||||
renderFavoriteChips();
|
||||
renderRecentSearches();
|
||||
|
||||
@@ -689,11 +839,6 @@ const App = (() => {
|
||||
'oepnv-navi:modes:departures',
|
||||
() => loadDepartures(),
|
||||
);
|
||||
journeyModeFilter = ModeFilter.create(
|
||||
document.getElementById('journey-mode-filter'),
|
||||
'oepnv-navi:modes:journey',
|
||||
() => {},
|
||||
);
|
||||
|
||||
const mapModeFilter = ModeFilter.create(
|
||||
document.getElementById('map-mode-filter'),
|
||||
|
||||
+336
-321
@@ -1,321 +1,336 @@
|
||||
// Live-Karte mit mehreren Modi:
|
||||
// - "radar": zeigt alle Fahrzeuge im aktuellen Kartenausschnitt (Standard),
|
||||
// gefiltert nach den gewählten Verkehrsmitteln
|
||||
// - "isolated": ein Fahrzeug wurde angeklickt -> nur dieses wird live weiter-
|
||||
// verfolgt (serverseitig via tripId gefiltert), sein Streckenverlauf
|
||||
// wird eingezeichnet, alle anderen Fahrzeuge sind ausgeblendet
|
||||
// - "trip": verfolgt ein bekanntes Fahrzeug (z.B. aus einer Verbindung heraus)
|
||||
// Nutzt bewusst reines OpenStreetMap ohne zusätzlichen Kartenstil.
|
||||
// Zusätzlich: createMiniMap() für kleine, unabhängige Vorschau-Karten in den
|
||||
// Verbindungsergebnissen (Routenplaner).
|
||||
|
||||
const LiveMap = (() => {
|
||||
let map = null;
|
||||
let radarLayer = null;
|
||||
let routeLayer = null;
|
||||
let userLayer = null;
|
||||
let tripMarker = null;
|
||||
|
||||
let mode = 'radar';
|
||||
let radarPollHandle = null;
|
||||
let tripPollHandle = null;
|
||||
let currentTripId = null;
|
||||
let isolatedVehicleMeta = null;
|
||||
let getModesParam = () => null;
|
||||
|
||||
function init() {
|
||||
if (map) return;
|
||||
|
||||
map = L.map('live-map', { zoomControl: true }).setView([52.5200, 13.4050], 13);
|
||||
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>-Mitwirkende',
|
||||
maxZoom: 19,
|
||||
}).addTo(map);
|
||||
|
||||
radarLayer = L.layerGroup().addTo(map);
|
||||
routeLayer = L.layerGroup().addTo(map);
|
||||
userLayer = L.layerGroup().addTo(map);
|
||||
|
||||
map.on('moveend', () => {
|
||||
if (mode === 'radar') refreshRadar();
|
||||
});
|
||||
}
|
||||
|
||||
function setModeFilter(fn) {
|
||||
getModesParam = fn;
|
||||
}
|
||||
|
||||
function vehicleIcon(label, bg, fg) {
|
||||
return L.divIcon({
|
||||
className: 'vehicle-marker',
|
||||
html: `<span style="background:${bg || '#F5A623'};color:${fg || '#fff'};">${label || '?'}</span>`,
|
||||
iconSize: [null, null],
|
||||
});
|
||||
}
|
||||
|
||||
function polylineToLatLngs(geojson) {
|
||||
if (!geojson || !geojson.features) return [];
|
||||
return geojson.features.map((f) => [f.geometry.coordinates[1], f.geometry.coordinates[0]]);
|
||||
}
|
||||
|
||||
async function refreshRadar() {
|
||||
if (!map || mode !== 'radar') return;
|
||||
const bounds = map.getBounds();
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getRadar({
|
||||
north: bounds.getNorth().toFixed(5),
|
||||
west: bounds.getWest().toFixed(5),
|
||||
south: bounds.getSouth().toFixed(5),
|
||||
east: bounds.getEast().toFixed(5),
|
||||
modes: getModesParam(),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Radar-Fehler:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
radarLayer.clearLayers();
|
||||
data.vehicles.forEach((v) => {
|
||||
if (v.latitude == null || v.longitude == null) return;
|
||||
const marker = L.marker([v.latitude, v.longitude], { icon: vehicleIcon(v.line, v.color, v.textColor) });
|
||||
marker.bindPopup(
|
||||
`<strong>${v.line || 'Linie unbekannt'}</strong><br>${v.direction || ''}<br>` +
|
||||
`<small>Nächster Halt: ${v.nextStopover || '–'}</small>`,
|
||||
);
|
||||
marker.on('click', () => isolateVehicle(v));
|
||||
marker.addTo(radarLayer);
|
||||
});
|
||||
}
|
||||
|
||||
function startRadar() {
|
||||
init();
|
||||
setMode('radar');
|
||||
refreshRadar();
|
||||
if (radarPollHandle) clearInterval(radarPollHandle);
|
||||
radarPollHandle = setInterval(refreshRadar, 15000);
|
||||
setTimeout(() => map && map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopRadar() {
|
||||
if (radarPollHandle) {
|
||||
clearInterval(radarPollHandle);
|
||||
radarPollHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshIsolated() {
|
||||
if (!map || mode !== 'isolated' || !currentTripId) return;
|
||||
const bounds = map.getBounds();
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getRadar({
|
||||
north: bounds.getNorth().toFixed(5),
|
||||
west: bounds.getWest().toFixed(5),
|
||||
south: bounds.getSouth().toFixed(5),
|
||||
east: bounds.getEast().toFixed(5),
|
||||
tripId: currentTripId,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Radar-Fehler (isoliert):', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
radarLayer.clearLayers();
|
||||
const v = data.vehicles[0];
|
||||
if (v && v.latitude != null && v.longitude != null) {
|
||||
const marker = L.marker([v.latitude, v.longitude], { icon: vehicleIcon(v.line, v.color, v.textColor) });
|
||||
marker.bindPopup(`<strong>${v.line || ''}</strong><br>${v.direction || ''}<br><small>Nächster Halt: ${v.nextStopover || '–'}</small>`);
|
||||
marker.addTo(radarLayer);
|
||||
}
|
||||
}
|
||||
|
||||
async function isolateVehicle(vehicle) {
|
||||
if (!vehicle || !vehicle.tripId) return;
|
||||
setMode('isolated');
|
||||
currentTripId = vehicle.tripId;
|
||||
isolatedVehicleMeta = { line: vehicle.line, color: vehicle.color, textColor: vehicle.textColor };
|
||||
updateIsolationBanner();
|
||||
|
||||
routeLayer.clearLayers();
|
||||
try {
|
||||
const trip = await API.getTrip(vehicle.tripId, { polyline: true });
|
||||
if (trip.polyline) {
|
||||
const latlngs = polylineToLatLngs(trip.polyline);
|
||||
if (latlngs.length > 0) {
|
||||
L.polyline(latlngs, { color: vehicle.color || '#F5A623', weight: 5, opacity: 0.85 }).addTo(routeLayer);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Trip-Polyline-Fehler:', err.message);
|
||||
}
|
||||
|
||||
refreshIsolated();
|
||||
if (radarPollHandle) clearInterval(radarPollHandle);
|
||||
radarPollHandle = setInterval(refreshIsolated, 10000);
|
||||
}
|
||||
|
||||
function clearIsolation() {
|
||||
currentTripId = null;
|
||||
isolatedVehicleMeta = null;
|
||||
updateIsolationBanner();
|
||||
startRadar();
|
||||
}
|
||||
|
||||
function updateIsolationBanner() {
|
||||
const banner = document.getElementById('map-isolation-banner');
|
||||
if (!banner) return;
|
||||
if (!isolatedVehicleMeta) {
|
||||
banner.classList.remove('is-visible');
|
||||
return;
|
||||
}
|
||||
const lineEl = document.getElementById('map-isolation-line');
|
||||
if (lineEl) {
|
||||
lineEl.textContent = isolatedVehicleMeta.line || '?';
|
||||
lineEl.style.background = isolatedVehicleMeta.color || '#F5A623';
|
||||
lineEl.style.color = isolatedVehicleMeta.textColor || '#fff';
|
||||
}
|
||||
banner.classList.add('is-visible');
|
||||
}
|
||||
|
||||
async function refreshTrip() {
|
||||
if (!currentTripId) return;
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getTrip(currentTripId, { polyline: !tripMarker });
|
||||
} catch (err) {
|
||||
console.error('Trip-Fehler:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.polyline && routeLayer) {
|
||||
routeLayer.clearLayers();
|
||||
const latlngs = polylineToLatLngs(data.polyline);
|
||||
if (latlngs.length > 0) {
|
||||
L.polyline(latlngs, { color: data.color || '#F5A623', weight: 4, opacity: 0.7 }).addTo(routeLayer);
|
||||
map.fitBounds(L.latLngBounds(latlngs), { padding: [30, 30] });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.currentLocation) {
|
||||
const pos = [data.currentLocation.latitude, data.currentLocation.longitude];
|
||||
if (tripMarker) {
|
||||
tripMarker.setLatLng(pos);
|
||||
} else {
|
||||
tripMarker = L.marker(pos, { icon: vehicleIcon(data.line, data.color, data.textColor) }).addTo(routeLayer);
|
||||
}
|
||||
tripMarker.bindPopup(`<strong>${data.line || ''}</strong><br>→ ${data.direction || ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
function trackTrip(tripId) {
|
||||
init();
|
||||
setMode('trip');
|
||||
currentTripId = tripId;
|
||||
tripMarker = null;
|
||||
routeLayer.clearLayers();
|
||||
|
||||
refreshTrip();
|
||||
if (tripPollHandle) clearInterval(tripPollHandle);
|
||||
tripPollHandle = setInterval(refreshTrip, 10000);
|
||||
setTimeout(() => map && map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopTracking() {
|
||||
if (tripPollHandle) {
|
||||
clearInterval(tripPollHandle);
|
||||
tripPollHandle = null;
|
||||
}
|
||||
currentTripId = null;
|
||||
tripMarker = null;
|
||||
}
|
||||
|
||||
function locateUser() {
|
||||
init();
|
||||
if (!navigator.geolocation) {
|
||||
alert('Geolocation wird von diesem Browser nicht unterstützt.');
|
||||
return;
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const { latitude, longitude } = pos.coords;
|
||||
userLayer.clearLayers();
|
||||
L.marker([latitude, longitude], {
|
||||
icon: L.divIcon({ className: 'user-location-marker', iconSize: [16, 16] }),
|
||||
}).addTo(userLayer);
|
||||
map.setView([latitude, longitude], 16);
|
||||
},
|
||||
(err) => alert('Standort konnte nicht ermittelt werden: ' + err.message),
|
||||
{ enableHighAccuracy: true, timeout: 10000 },
|
||||
);
|
||||
}
|
||||
|
||||
function setMode(newMode) {
|
||||
if (mode === newMode) return;
|
||||
if (mode === 'radar') stopRadar();
|
||||
if (mode === 'isolated') stopRadar();
|
||||
if (mode === 'trip') stopTracking();
|
||||
if (newMode === 'radar') routeLayer.clearLayers();
|
||||
mode = newMode;
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
if (mode === 'radar' || mode === 'idle') startRadar();
|
||||
else if (map) setTimeout(() => map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
stopRadar();
|
||||
stopTracking();
|
||||
}
|
||||
|
||||
function createMiniMap(containerId, journey) {
|
||||
const miniMap = L.map(containerId, {
|
||||
zoomControl: false,
|
||||
attributionControl: false,
|
||||
dragging: true,
|
||||
scrollWheelZoom: false,
|
||||
tap: true,
|
||||
}).setView([52.5200, 13.4050], 12);
|
||||
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap-Mitwirkende',
|
||||
maxZoom: 19,
|
||||
}).addTo(miniMap);
|
||||
|
||||
const allPoints = [];
|
||||
(journey.legs || []).forEach((leg) => {
|
||||
if (!leg.polyline) return;
|
||||
const latlngs = polylineToLatLngs(leg.polyline);
|
||||
if (latlngs.length === 0) return;
|
||||
L.polyline(latlngs, {
|
||||
color: leg.walking ? '#8E99A6' : leg.color || '#F5A623',
|
||||
weight: leg.walking ? 3 : 4,
|
||||
dashArray: leg.walking ? '5, 7' : null,
|
||||
opacity: 0.9,
|
||||
}).addTo(miniMap);
|
||||
allPoints.push(...latlngs);
|
||||
});
|
||||
|
||||
if (allPoints.length > 0) {
|
||||
miniMap.fitBounds(L.latLngBounds(allPoints), { padding: [16, 16] });
|
||||
}
|
||||
|
||||
setTimeout(() => miniMap.invalidateSize(), 50);
|
||||
return miniMap;
|
||||
}
|
||||
|
||||
return {
|
||||
startPolling,
|
||||
stopPolling,
|
||||
trackTrip,
|
||||
setModeFilter,
|
||||
clearIsolation,
|
||||
locateUser,
|
||||
createMiniMap,
|
||||
};
|
||||
})();
|
||||
// Live-Karte mit mehreren Modi:
|
||||
// - "radar": zeigt alle Fahrzeuge im aktuellen Kartenausschnitt (Standard),
|
||||
// gefiltert nach den gewählten Verkehrsmitteln
|
||||
// - "isolated": ein Fahrzeug wurde angeklickt -> nur dieses wird live weiter-
|
||||
// verfolgt (serverseitig via tripId gefiltert), sein Streckenverlauf
|
||||
// wird eingezeichnet, alle anderen Fahrzeuge sind ausgeblendet
|
||||
// - "trip": verfolgt ein bekanntes Fahrzeug (z.B. aus einer Verbindung heraus)
|
||||
// Nutzt bewusst reines OpenStreetMap ohne zusätzlichen Kartenstil.
|
||||
// Zusätzlich: createMiniMap() für kleine, unabhängige Vorschau-Karten in den
|
||||
// Verbindungsergebnissen (Routenplaner).
|
||||
|
||||
const LiveMap = (() => {
|
||||
let map = null;
|
||||
let radarLayer = null;
|
||||
let routeLayer = null;
|
||||
let userLayer = null;
|
||||
let tripMarker = null;
|
||||
|
||||
let mode = 'radar';
|
||||
let radarPollHandle = null;
|
||||
let tripPollHandle = null;
|
||||
let currentTripId = null;
|
||||
let isolatedVehicleMeta = null; // { line, color, textColor } für die Banner-Anzeige
|
||||
let getModesParam = () => null; // wird von außen (ModeFilter) gesetzt
|
||||
|
||||
function init() {
|
||||
if (map) return;
|
||||
|
||||
map = L.map('live-map', { zoomControl: true }).setView([52.5200, 13.4050], 13);
|
||||
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>-Mitwirkende',
|
||||
maxZoom: 19,
|
||||
}).addTo(map);
|
||||
|
||||
radarLayer = L.layerGroup().addTo(map);
|
||||
routeLayer = L.layerGroup().addTo(map);
|
||||
userLayer = L.layerGroup().addTo(map);
|
||||
|
||||
map.on('moveend', () => {
|
||||
if (mode === 'radar') refreshRadar();
|
||||
});
|
||||
}
|
||||
|
||||
function setModeFilter(fn) {
|
||||
getModesParam = fn;
|
||||
}
|
||||
|
||||
function vehicleIcon(label, bg, fg) {
|
||||
return L.divIcon({
|
||||
className: 'vehicle-marker',
|
||||
html: `<span style="background:${bg || '#F5A623'};color:${fg || '#fff'};">${label || '?'}</span>`,
|
||||
iconSize: [null, null],
|
||||
});
|
||||
}
|
||||
|
||||
function polylineToLatLngs(geojson) {
|
||||
if (!geojson || !geojson.features) return [];
|
||||
return geojson.features.map((f) => [f.geometry.coordinates[1], f.geometry.coordinates[0]]);
|
||||
}
|
||||
|
||||
// ---------- Radar-Modus (Standard: alle Fahrzeuge im Ausschnitt) ----------
|
||||
|
||||
async function refreshRadar() {
|
||||
if (!map || mode !== 'radar') return;
|
||||
const bounds = map.getBounds();
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getRadar({
|
||||
north: bounds.getNorth().toFixed(5),
|
||||
west: bounds.getWest().toFixed(5),
|
||||
south: bounds.getSouth().toFixed(5),
|
||||
east: bounds.getEast().toFixed(5),
|
||||
modes: getModesParam(),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Radar-Fehler:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
radarLayer.clearLayers();
|
||||
data.vehicles.forEach((v) => {
|
||||
if (v.latitude == null || v.longitude == null) return;
|
||||
const marker = L.marker([v.latitude, v.longitude], { icon: vehicleIcon(v.line, v.color, v.textColor) });
|
||||
marker.bindPopup(
|
||||
`<strong>${v.line || 'Linie unbekannt'}</strong><br>${v.direction || ''}<br>` +
|
||||
`<small>Nächster Halt: ${v.nextStopover || '–'}</small>`,
|
||||
);
|
||||
// Klick auf eine Linie: isoliert sie (alle anderen Fahrzeuge ausblenden,
|
||||
// Streckenverlauf einzeichnen, live weiterverfolgen).
|
||||
marker.on('click', () => isolateVehicle(v));
|
||||
marker.addTo(radarLayer);
|
||||
});
|
||||
}
|
||||
|
||||
function startRadar() {
|
||||
init();
|
||||
setMode('radar');
|
||||
refreshRadar();
|
||||
if (radarPollHandle) clearInterval(radarPollHandle);
|
||||
radarPollHandle = setInterval(refreshRadar, 15000);
|
||||
setTimeout(() => map && map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopRadar() {
|
||||
if (radarPollHandle) {
|
||||
clearInterval(radarPollHandle);
|
||||
radarPollHandle = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Isolations-Modus (eine angeklickte Linie live verfolgen) ----------
|
||||
|
||||
async function refreshIsolated() {
|
||||
if (!map || mode !== 'isolated' || !currentTripId) return;
|
||||
const bounds = map.getBounds();
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getRadar({
|
||||
north: bounds.getNorth().toFixed(5),
|
||||
west: bounds.getWest().toFixed(5),
|
||||
south: bounds.getSouth().toFixed(5),
|
||||
east: bounds.getEast().toFixed(5),
|
||||
tripId: currentTripId,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Radar-Fehler (isoliert):', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
radarLayer.clearLayers();
|
||||
const v = data.vehicles[0];
|
||||
if (v && v.latitude != null && v.longitude != null) {
|
||||
const marker = L.marker([v.latitude, v.longitude], { icon: vehicleIcon(v.line, v.color, v.textColor) });
|
||||
marker.bindPopup(`<strong>${v.line || ''}</strong><br>${v.direction || ''}<br><small>Nächster Halt: ${v.nextStopover || '–'}</small>`);
|
||||
marker.addTo(radarLayer);
|
||||
}
|
||||
}
|
||||
|
||||
async function isolateVehicle(vehicle) {
|
||||
if (!vehicle || !vehicle.tripId) return;
|
||||
setMode('isolated');
|
||||
currentTripId = vehicle.tripId;
|
||||
isolatedVehicleMeta = { line: vehicle.line, color: vehicle.color, textColor: vehicle.textColor };
|
||||
updateIsolationBanner();
|
||||
|
||||
routeLayer.clearLayers();
|
||||
try {
|
||||
const trip = await API.getTrip(vehicle.tripId, { polyline: true });
|
||||
if (trip.polyline) {
|
||||
const latlngs = polylineToLatLngs(trip.polyline);
|
||||
if (latlngs.length > 0) {
|
||||
L.polyline(latlngs, { color: vehicle.color || '#F5A623', weight: 5, opacity: 0.85 }).addTo(routeLayer);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Trip-Polyline-Fehler:', err.message);
|
||||
}
|
||||
|
||||
refreshIsolated();
|
||||
if (radarPollHandle) clearInterval(radarPollHandle);
|
||||
radarPollHandle = setInterval(refreshIsolated, 10000);
|
||||
}
|
||||
|
||||
function clearIsolation() {
|
||||
currentTripId = null;
|
||||
isolatedVehicleMeta = null;
|
||||
updateIsolationBanner();
|
||||
startRadar();
|
||||
}
|
||||
|
||||
function updateIsolationBanner() {
|
||||
const banner = document.getElementById('map-isolation-banner');
|
||||
if (!banner) return;
|
||||
if (!isolatedVehicleMeta) {
|
||||
banner.classList.remove('is-visible');
|
||||
return;
|
||||
}
|
||||
const lineEl = document.getElementById('map-isolation-line');
|
||||
if (lineEl) {
|
||||
lineEl.textContent = isolatedVehicleMeta.line || '?';
|
||||
lineEl.style.background = isolatedVehicleMeta.color || '#F5A623';
|
||||
lineEl.style.color = isolatedVehicleMeta.textColor || '#fff';
|
||||
}
|
||||
banner.classList.add('is-visible');
|
||||
}
|
||||
|
||||
// ---------- Trip-Modus (bekanntes Fahrzeug aus einer Verbindung heraus verfolgen) ----------
|
||||
|
||||
async function refreshTrip() {
|
||||
if (!currentTripId) return;
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await API.getTrip(currentTripId, { polyline: !tripMarker });
|
||||
} catch (err) {
|
||||
console.error('Trip-Fehler:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.polyline && routeLayer) {
|
||||
routeLayer.clearLayers();
|
||||
const latlngs = polylineToLatLngs(data.polyline);
|
||||
if (latlngs.length > 0) {
|
||||
L.polyline(latlngs, { color: data.color || '#F5A623', weight: 4, opacity: 0.7 }).addTo(routeLayer);
|
||||
map.fitBounds(L.latLngBounds(latlngs), { padding: [30, 30] });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.currentLocation) {
|
||||
const pos = [data.currentLocation.latitude, data.currentLocation.longitude];
|
||||
if (tripMarker) {
|
||||
tripMarker.setLatLng(pos);
|
||||
} else {
|
||||
tripMarker = L.marker(pos, { icon: vehicleIcon(data.line, data.color, data.textColor) }).addTo(routeLayer);
|
||||
}
|
||||
tripMarker.bindPopup(`<strong>${data.line || ''}</strong><br>→ ${data.direction || ''}`);
|
||||
}
|
||||
}
|
||||
|
||||
function trackTrip(tripId) {
|
||||
init();
|
||||
setMode('trip');
|
||||
currentTripId = tripId;
|
||||
tripMarker = null;
|
||||
routeLayer.clearLayers();
|
||||
|
||||
refreshTrip();
|
||||
if (tripPollHandle) clearInterval(tripPollHandle);
|
||||
tripPollHandle = setInterval(refreshTrip, 10000);
|
||||
setTimeout(() => map && map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopTracking() {
|
||||
if (tripPollHandle) {
|
||||
clearInterval(tripPollHandle);
|
||||
tripPollHandle = null;
|
||||
}
|
||||
currentTripId = null;
|
||||
tripMarker = null;
|
||||
}
|
||||
|
||||
// ---------- Standort ----------
|
||||
|
||||
function locateUser() {
|
||||
init();
|
||||
if (!navigator.geolocation) {
|
||||
alert('Geolocation wird von diesem Browser nicht unterstützt.');
|
||||
return;
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const { latitude, longitude } = pos.coords;
|
||||
userLayer.clearLayers();
|
||||
L.marker([latitude, longitude], {
|
||||
icon: L.divIcon({ className: 'user-location-marker', iconSize: [16, 16] }),
|
||||
}).addTo(userLayer);
|
||||
map.setView([latitude, longitude], 16);
|
||||
},
|
||||
(err) => alert('Standort konnte nicht ermittelt werden: ' + err.message),
|
||||
{ enableHighAccuracy: true, timeout: 10000 },
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Modus-Verwaltung ----------
|
||||
|
||||
function setMode(newMode) {
|
||||
if (mode === newMode) return;
|
||||
if (mode === 'radar') stopRadar();
|
||||
if (mode === 'isolated') stopRadar();
|
||||
if (mode === 'trip') stopTracking();
|
||||
if (newMode === 'radar') routeLayer.clearLayers();
|
||||
mode = newMode;
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
// Rückwärtskompatibler Einstieg: Karten-Tab wurde geöffnet.
|
||||
if (mode === 'radar' || mode === 'idle') startRadar();
|
||||
else if (map) setTimeout(() => map.invalidateSize(), 150);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
stopRadar();
|
||||
stopTracking();
|
||||
}
|
||||
|
||||
// ---------- Mini-Karte für Verbindungsvorschau (Routenplaner) ----------
|
||||
|
||||
function createMiniMap(containerId, journey) {
|
||||
const miniMap = L.map(containerId, {
|
||||
zoomControl: false,
|
||||
attributionControl: false,
|
||||
dragging: true,
|
||||
scrollWheelZoom: false,
|
||||
tap: true,
|
||||
}).setView([52.5200, 13.4050], 12);
|
||||
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
||||
attribution: '© OpenStreetMap-Mitwirkende',
|
||||
maxZoom: 19,
|
||||
}).addTo(miniMap);
|
||||
|
||||
const allPoints = [];
|
||||
(journey.legs || []).forEach((leg) => {
|
||||
if (!leg.polyline) return;
|
||||
const latlngs = polylineToLatLngs(leg.polyline);
|
||||
if (latlngs.length === 0) return;
|
||||
L.polyline(latlngs, {
|
||||
color: leg.walking ? '#8E99A6' : leg.color || '#F5A623',
|
||||
weight: leg.walking ? 3 : 4,
|
||||
dashArray: leg.walking ? '5, 7' : null,
|
||||
opacity: 0.9,
|
||||
}).addTo(miniMap);
|
||||
allPoints.push(...latlngs);
|
||||
});
|
||||
|
||||
if (allPoints.length > 0) {
|
||||
miniMap.fitBounds(L.latLngBounds(allPoints), { padding: [16, 16] });
|
||||
}
|
||||
|
||||
setTimeout(() => miniMap.invalidateSize(), 50);
|
||||
return miniMap;
|
||||
}
|
||||
|
||||
return {
|
||||
startPolling,
|
||||
stopPolling,
|
||||
trackTrip,
|
||||
setModeFilter,
|
||||
clearIsolation,
|
||||
locateUser,
|
||||
createMiniMap,
|
||||
};
|
||||
})();
|
||||
+150
-149
@@ -1,149 +1,150 @@
|
||||
// Modal, das beim Klick auf eine Abfahrtszeile oder einen Verbindungsabschnitt
|
||||
// geöffnet wird: zeigt Linie, Richtung, eine kleine Karte mit dem Streckenverlauf
|
||||
// und alle Zwischenhalte mit Zeiten/Verspätungen.
|
||||
|
||||
const TripModal = (() => {
|
||||
let backdrop = null;
|
||||
let miniMap = null;
|
||||
|
||||
function ensureBackdrop() {
|
||||
if (backdrop) return backdrop;
|
||||
backdrop = document.createElement('div');
|
||||
backdrop.className = 'trip-modal-backdrop';
|
||||
backdrop.hidden = true;
|
||||
backdrop.innerHTML = `
|
||||
<div class="trip-modal" role="dialog" aria-modal="true" aria-label="Fahrt-Details">
|
||||
<div class="trip-modal__header">
|
||||
<span class="trip-modal__line" id="trip-modal-line"></span>
|
||||
<div class="trip-modal__title">
|
||||
<strong id="trip-modal-direction"></strong>
|
||||
<small id="trip-modal-meta"></small>
|
||||
</div>
|
||||
<button class="trip-modal__close" type="button" aria-label="Schließen">×</button>
|
||||
</div>
|
||||
<div class="trip-modal__map" id="trip-modal-map"></div>
|
||||
<div class="trip-modal__body" id="trip-modal-body">
|
||||
<div class="trip-modal__loading"><span class="spinner"></span>Lade Fahrt-Details…</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(backdrop);
|
||||
|
||||
backdrop.querySelector('.trip-modal__close').addEventListener('click', close);
|
||||
backdrop.addEventListener('click', (e) => {
|
||||
if (e.target === backdrop) close();
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && !backdrop.hidden) close();
|
||||
});
|
||||
|
||||
return backdrop;
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (!backdrop) return;
|
||||
backdrop.hidden = true;
|
||||
if (miniMap) {
|
||||
miniMap.remove();
|
||||
miniMap = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
if (!iso) return null;
|
||||
return new Date(iso).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function renderStopover(s, isCurrentOrNext) {
|
||||
const time = s.departure || s.arrival || s.plannedDeparture || s.plannedArrival;
|
||||
const plannedTime = s.plannedDeparture || s.plannedArrival;
|
||||
const delay = s.departureDelay ?? s.arrivalDelay;
|
||||
|
||||
let timeHtml;
|
||||
if (s.cancelled) {
|
||||
timeHtml = `<span class="trip-stopover__time trip-stopover__time--cancelled">${formatTime(plannedTime) || '–'}</span>`;
|
||||
} else if (delay && delay > 0) {
|
||||
timeHtml = `<span class="trip-stopover__time trip-stopover__time--delayed">${formatTime(time)} (+${Math.round(delay / 60)})</span>`;
|
||||
} else {
|
||||
timeHtml = `<span class="trip-stopover__time">${formatTime(time) || '–'}</span>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="trip-stopover ${isCurrentOrNext ? 'trip-stopover--current' : ''} ${s.cancelled ? 'trip-stopover--cancelled' : ''}">
|
||||
<div class="trip-stopover__row">
|
||||
<span class="trip-stopover__name">${s.name || ''}</span>
|
||||
${timeHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function open(tripId) {
|
||||
if (!tripId) return;
|
||||
const el = ensureBackdrop();
|
||||
el.hidden = false;
|
||||
|
||||
document.getElementById('trip-modal-line').textContent = '…';
|
||||
document.getElementById('trip-modal-line').style.background = '#8E99A6';
|
||||
document.getElementById('trip-modal-direction').textContent = '';
|
||||
document.getElementById('trip-modal-meta').textContent = '';
|
||||
document.getElementById('trip-modal-body').innerHTML = '<div class="trip-modal__loading"><span class="spinner"></span>Lade Fahrt-Details…</div>';
|
||||
|
||||
let trip;
|
||||
try {
|
||||
trip = await API.getTrip(tripId, { polyline: true });
|
||||
} catch (err) {
|
||||
document.getElementById('trip-modal-body').innerHTML = `<div class="trip-modal__error">⚠ ${err.message}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const lineEl = document.getElementById('trip-modal-line');
|
||||
lineEl.textContent = trip.line || '?';
|
||||
lineEl.style.background = trip.color || '#8E99A6';
|
||||
lineEl.style.color = trip.textColor || '#fff';
|
||||
|
||||
document.getElementById('trip-modal-direction').textContent = `→ ${trip.direction || trip.destination || ''}`;
|
||||
document.getElementById('trip-modal-meta').textContent = trip.cancelled
|
||||
? 'Fahrt fällt aus'
|
||||
: `${trip.origin || ''} → ${trip.destination || ''}`;
|
||||
|
||||
if (miniMap) { miniMap.remove(); miniMap = null; }
|
||||
if (trip.polyline) {
|
||||
setTimeout(() => {
|
||||
miniMap = LiveMap.createMiniMap('trip-modal-map', {
|
||||
legs: [{ polyline: trip.polyline, walking: false, color: trip.color }],
|
||||
});
|
||||
if (trip.currentLocation) {
|
||||
L.marker([trip.currentLocation.latitude, trip.currentLocation.longitude], {
|
||||
icon: L.divIcon({
|
||||
className: 'vehicle-marker',
|
||||
html: `<span style="background:${trip.color || '#F5A623'};color:${trip.textColor || '#fff'};">${trip.line || '?'}</span>`,
|
||||
iconSize: [null, null],
|
||||
}),
|
||||
}).addTo(miniMap);
|
||||
}
|
||||
}, 50);
|
||||
} else {
|
||||
document.getElementById('trip-modal-map').innerHTML = '';
|
||||
}
|
||||
|
||||
const stopovers = trip.stopovers || [];
|
||||
const now = Date.now();
|
||||
let currentIndex = stopovers.findIndex((s) => {
|
||||
const t = s.departure || s.plannedDeparture;
|
||||
return t && new Date(t).getTime() >= now;
|
||||
});
|
||||
if (currentIndex === -1) currentIndex = stopovers.length - 1;
|
||||
|
||||
const bodyHtml = `
|
||||
<div class="trip-stopovers">
|
||||
${stopovers.map((s, i) => renderStopover(s, i === currentIndex)).join('')}
|
||||
</div>
|
||||
`;
|
||||
document.getElementById('trip-modal-body').innerHTML = stopovers.length
|
||||
? bodyHtml
|
||||
: '<div class="trip-modal__loading">Keine Zwischenhalte verfügbar.</div>';
|
||||
}
|
||||
|
||||
return { open, close };
|
||||
})();
|
||||
// Modal, das beim Klick auf eine Abfahrtszeile oder einen Verbindungsabschnitt
|
||||
// geöffnet wird: zeigt Linie, Richtung, eine kleine Karte mit dem Streckenverlauf
|
||||
// und alle Zwischenhalte mit Zeiten/Verspätungen.
|
||||
|
||||
const TripModal = (() => {
|
||||
let backdrop = null;
|
||||
let miniMap = null;
|
||||
|
||||
function ensureBackdrop() {
|
||||
if (backdrop) return backdrop;
|
||||
backdrop = document.createElement('div');
|
||||
backdrop.className = 'trip-modal-backdrop';
|
||||
backdrop.hidden = true;
|
||||
backdrop.innerHTML = `
|
||||
<div class="trip-modal" role="dialog" aria-modal="true" aria-label="Fahrt-Details">
|
||||
<div class="trip-modal__header">
|
||||
<span class="trip-modal__line" id="trip-modal-line"></span>
|
||||
<div class="trip-modal__title">
|
||||
<strong id="trip-modal-direction"></strong>
|
||||
<small id="trip-modal-meta"></small>
|
||||
</div>
|
||||
<button class="trip-modal__close" type="button" aria-label="Schließen">×</button>
|
||||
</div>
|
||||
<div class="trip-modal__map" id="trip-modal-map"></div>
|
||||
<div class="trip-modal__body" id="trip-modal-body">
|
||||
<div class="trip-modal__loading"><span class="spinner"></span>Lade Fahrt-Details…</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(backdrop);
|
||||
|
||||
backdrop.querySelector('.trip-modal__close').addEventListener('click', close);
|
||||
backdrop.addEventListener('click', (e) => {
|
||||
if (e.target === backdrop) close();
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && !backdrop.hidden) close();
|
||||
});
|
||||
|
||||
return backdrop;
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (!backdrop) return;
|
||||
backdrop.hidden = true;
|
||||
if (miniMap) {
|
||||
miniMap.remove();
|
||||
miniMap = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
if (!iso) return null;
|
||||
return new Date(iso).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function renderStopover(s, isCurrentOrNext) {
|
||||
const time = s.departure || s.arrival || s.plannedDeparture || s.plannedArrival;
|
||||
const plannedTime = s.plannedDeparture || s.plannedArrival;
|
||||
const delay = s.departureDelay ?? s.arrivalDelay;
|
||||
|
||||
let timeHtml;
|
||||
if (s.cancelled) {
|
||||
timeHtml = `<span class="trip-stopover__time trip-stopover__time--cancelled">${formatTime(plannedTime) || '–'}</span>`;
|
||||
} else if (delay && delay > 0) {
|
||||
timeHtml = `<span class="trip-stopover__time trip-stopover__time--delayed">${formatTime(time)} (+${Math.round(delay / 60)})</span>`;
|
||||
} else {
|
||||
timeHtml = `<span class="trip-stopover__time">${formatTime(time) || '–'}</span>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="trip-stopover ${isCurrentOrNext ? 'trip-stopover--current' : ''} ${s.cancelled ? 'trip-stopover--cancelled' : ''}">
|
||||
<div class="trip-stopover__row">
|
||||
<span class="trip-stopover__name">${s.name || ''}</span>
|
||||
${timeHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function open(tripId) {
|
||||
if (!tripId) return;
|
||||
const el = ensureBackdrop();
|
||||
el.hidden = false;
|
||||
|
||||
document.getElementById('trip-modal-line').textContent = '…';
|
||||
document.getElementById('trip-modal-line').style.background = '#8E99A6';
|
||||
document.getElementById('trip-modal-direction').textContent = '';
|
||||
document.getElementById('trip-modal-meta').textContent = '';
|
||||
document.getElementById('trip-modal-body').innerHTML = '<div class="trip-modal__loading"><span class="spinner"></span>Lade Fahrt-Details…</div>';
|
||||
|
||||
let trip;
|
||||
try {
|
||||
trip = await API.getTrip(tripId, { polyline: true });
|
||||
} catch (err) {
|
||||
document.getElementById('trip-modal-body').innerHTML = `<div class="trip-modal__error">⚠ ${err.message}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const lineEl = document.getElementById('trip-modal-line');
|
||||
lineEl.textContent = trip.line || '?';
|
||||
lineEl.style.background = trip.color || '#8E99A6';
|
||||
lineEl.style.color = trip.textColor || '#fff';
|
||||
|
||||
document.getElementById('trip-modal-direction').textContent = `→ ${trip.direction || trip.destination || ''}`;
|
||||
document.getElementById('trip-modal-meta').textContent = trip.cancelled
|
||||
? 'Fahrt fällt aus'
|
||||
: `${trip.origin || ''} → ${trip.destination || ''}`;
|
||||
|
||||
// Mini-Karte mit dem Streckenverlauf zeichnen
|
||||
if (miniMap) { miniMap.remove(); miniMap = null; }
|
||||
if (trip.polyline) {
|
||||
setTimeout(() => {
|
||||
miniMap = LiveMap.createMiniMap('trip-modal-map', {
|
||||
legs: [{ polyline: trip.polyline, walking: false, color: trip.color }],
|
||||
});
|
||||
if (trip.currentLocation) {
|
||||
L.marker([trip.currentLocation.latitude, trip.currentLocation.longitude], {
|
||||
icon: L.divIcon({
|
||||
className: 'vehicle-marker',
|
||||
html: `<span style="background:${trip.color || '#F5A623'};color:${trip.textColor || '#fff'};">${trip.line || '?'}</span>`,
|
||||
iconSize: [null, null],
|
||||
}),
|
||||
}).addTo(miniMap);
|
||||
}
|
||||
}, 50);
|
||||
} else {
|
||||
document.getElementById('trip-modal-map').innerHTML = '';
|
||||
}
|
||||
|
||||
const stopovers = trip.stopovers || [];
|
||||
const now = Date.now();
|
||||
let currentIndex = stopovers.findIndex((s) => {
|
||||
const t = s.departure || s.plannedDeparture;
|
||||
return t && new Date(t).getTime() >= now;
|
||||
});
|
||||
if (currentIndex === -1) currentIndex = stopovers.length - 1;
|
||||
|
||||
const bodyHtml = `
|
||||
<div class="trip-stopovers">
|
||||
${stopovers.map((s, i) => renderStopover(s, i === currentIndex)).join('')}
|
||||
</div>
|
||||
`;
|
||||
document.getElementById('trip-modal-body').innerHTML = stopovers.length
|
||||
? bodyHtml
|
||||
: '<div class="trip-modal__loading">Keine Zwischenhalte verfügbar.</div>';
|
||||
}
|
||||
|
||||
return { open, close };
|
||||
})();
|
||||
Reference in new issue
Block a user