-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtecmap.html
461 lines (379 loc) · 17.7 KB
/
tecmap.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TECmap : Carte des transports en commun (TEC) en temps réel</title>
<script src="config.js"></script> <!-- load configuration variables -->
<!-- Leaflet CSS & JS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css">
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<!-- load local transit data: stops and trips -->
<script src="data/stops.js"></script> <!-- loads stopsData -->
<!-- Leaflet geolocalisation control -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.locatecontrol/0.79.0/L.Control.Locate.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-locatecontrol/0.79.0/L.Control.Locate.min.js"></script>
<!-- Style FontAwesome pour les icônes -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
#map { height: 98vh; }
.custom-user-marker {
font-size: 44px;
color: blue;
text-shadow: 1px 1px 2px white;
}
/* Classes dynamiques pour changer la couleur des icônes */
.bus-icon-black { color: black; }
.bus-icon-green { color: green; }
.bus-icon-orange { color: orange; }
.bus-icon-red { color: red; }
.bus-icon-grey { color: grey; }
.bus-icon {
font-size: 24px;
text-shadow:
-2px -2px 2px white,
2px -2px 2px white,
-2px 2px 2px white,
2px 2px 2px white;
border-radius: 50%;
background: white;
padding: 5px;
}
.bus-marker {
position: relative;
width: 40px;
height: 40px;
background: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.bus-marker i {
font-size: 18px;
color: black;
}
.bus-number {
position: absolute;
bottom: -15px;
left: 50%;
transform: translateX(-50%);
font-size: 12px;
font-weight: bold;
background: white;
padding: 2px 5px;
border-radius: 5px;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
}
button {
background: none;
border: none;
font-size: 14px;
cursor: pointer;
}
.leaflet-popup-content {
min-width: 250px;
max-width: 400px;
white-space: normal;
}
</style>
</head>
<body>
<!-- Filter area -->
<div id="filter-container" style="position: absolute; top: 10px; left: 50px; background: white; padding: 5px; z-index: 1000;">
<div style="display: flex; align-items: center; gap: 5px;">
<input type="text" id="busFilter" placeholder="Filtrer par ligne de bus" oninput="fetchRealTimeBusData()">
<span><a href="https://busmaps.com/en/feedinfo/belgium/TEC-Transit/tec-transit/routes">?</a></span>
<button onclick="clearFilter()">❌</button>
</div>
<p style="margin: 0;">Nombre de bus visibles: <span id="busCount">0</span></p>
</div>
<div id="map"></div>
<script>
let busMarkers = {}; // Marqueurs des bus
// Fonction pour calculer le numéro de la semaine actuelle (ISO 8601)
function getISOWeekNumber(date = new Date()) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); // première semaine de l'année est la semaine où tombe le premier jeudi
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
}
// Fonction pour charger dynamiquement le fichier des horaires en fonction du jour et de la semaine (congés scolaires ou pas)
function loadScheduleFile() {
const holidayWeeks = [1, 9, 10, 18, 19, 27, 28, 29, 30, 31, 32, 33, 34, 43, 44, 52]; //Belgium holiday weeks in 2025
const dayOfWeek = new Date().getDay();
const currentWeek = getISOWeekNumber();
let suffix = holidayWeeks.includes(currentWeek) ? "_VAC" : "";
let scriptFile = "data/stop_times-SEM"+suffix+".js"; // Par défaut, horaires pour les jours de la semaine
if (dayOfWeek === 0) { // Dimanche
scriptFile = "data/stop_times-DIM"+suffix+".js";
} else if (dayOfWeek === 6) { // Samedi
scriptFile = "data/stop_times-SAM"+suffix+".js";
} else if (dayOfWeek === 3) { // Mercredi
scriptFile = "data/stop_times-MER"+suffix+".js";
}
// Créer et insérer dynamiquement un script
const script = document.createElement("script");
script.src = scriptFile;
script.onload = () => console.log(`Horaires théoriques chargés depuis ${scriptFile}`);
script.onerror = () => console.error(`Erreur de chargement du fichier ${scriptFile}`);
document.head.appendChild(script);
}
//Chargement des horaires theoriques
loadScheduleFile();
// ---------------------------------------------------------------------------------------------
// Initialisation de la carte, coordonnees par defaut ou demande de geolocalisation
const defaultCoords = [50.63, 5.56];
var osmLayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
var osmHOTLayer = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© HOT hosted by OSM France'});
var cyclOSMLayer = L.tileLayer('https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
{ maxZoom: 19,
attribution: '© <a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases">CyclOSM</a>'});
var opnvLayer = L.tileLayer('https://tile.memomaps.de/tilegen/{z}/{x}/{y}.png',
{ maxZoom: 19,
attribution: '© Öpnvkarte'});
// tileLayer from thunderforest can be used using an apikey
if (TILE_API_KEY) {
var transportTileLayer = L.tileLayer('https://tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey='+TILE_API_KEY, {
attribution: '© <a href="https://www.thunderforest.com/maps/transport/">Thunderforest</a>',
maxZoom: 22
});
var cycleMapTileLayer = L.tileLayer('https://tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey='+TILE_API_KEY, {
attribution: '© <a href="https://www.thunderforest.com/maps/transport/">Thunderforest</a>',
maxZoom: 22});
var defaultLayer = transportTileLayer;
}
else { // we use opnvLayer as default
var transportTileLayer = opnvLayer;
var cycleMapTileLayer = opnvLayer;
var defaultLayer = opnvLayer;
}
var map = L.map('map', {
center: defaultCoords,//[39.73, -104.99],
zoom: 16,
layers: defaultLayer
});
var baseMaps = {
"OpenStreetMap": osmLayer,
"OpenStreetMap.HOT": osmHOTLayer,
"CyclOSM": cyclOSMLayer,
"CyleMap (Thunderforest)": cycleMapTileLayer,
"Transport map (Öpnvkarte)": opnvLayer,
"TransportMap (Thunderforest)": transportTileLayer,
};
var layerControl = L.control.layers(baseMaps).addTo(map);
// Ajouter le bouton de localisation
lc = L.control.locate({
follow: true, // Suit la position de l'utilisateur en temps réel
keepCurrentZoomLevel: true, // Ne change pas le niveau de zoom actuel
icon: "fa-solid fa-location-dot", //"fas fa-map-marker-alt", // Icône FontAwesome
strings: {
title: "Voir ma position"
},
}).addTo(map);
// ---------------------------------------------------------------------------------------------
// Fonctions utilitaires
// Fonction pour nettoyer le filtre
function clearFilter() {
document.getElementById('busFilter').value = '';
fetchRealTimeBusData(); // Recupere data apres la suppression du filtre
}
// Calcul du nombre de minutes depuis le démarrage du bus
// not used anymore
function getTimeSinceStart(startTime) {
const now = new Date(); // Heure actuelle
const currentDate = now.toISOString().split('T')[0];
const fullStartTime = `${currentDate}T${startTime}`;
const startDate = new Date(fullStartTime); // Convertir startTime en objet Date
const differenceInMillis = now - startDate; // Différence en millisecondes
const differenceInMinutes = Math.floor(differenceInMillis / 60000); // Convertir en minutes
return differenceInMinutes;
}
// Recupere le nom lisible d'un arret
function getStopName(stopId, stopsMap) {
if (stopId) {
return stopsMap[stopId] || "Arrêt inconnu";
}
}
// Détermine la couleur de l'icône du bus en fonction de la vitesse
function getBusSpeedColor(speed) {
if (speed === null) return "grey";
else if (speed < 10) return "black";
else if (speed >= 10 && speed <= 50) return "green";
else if (speed > 50 && speed <= 70) return "orange";
else return "red";
}
// Détermine la couleur de l'icône du bus en fonction de son retard
function getBusDelayColor(delay) {
if (delay > 0 && delay < 5) return "orange";
else if (delay >= 5) return "red";
else return "green";
}
// Convertir timestamp UNIX en temps lisible
function timestampToTime(timestamp) {
const date = new Date(timestamp * 1000); // Convertir en millisecondes
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
// Convertir temps lisible en timestamp UNIX
function timeToUnixTimestamp(timeStr, referenceDate = new Date()) {
const [hours, minutes] = timeStr.split(":").map(Number); //time is formatted HH:MM
// Copier la date de référence Unix et mettre l'heure indiquée
const date = new Date(referenceDate);
date.setHours(hours, minutes, 0, 0);
// Retourner le timestamp Unix en secondes
return Math.floor(date.getTime() / 1000);
}
// Calcule le retard d'un bus etant donnee le trajet theorique (schedule), le prochain arrêt, et le timestamp temps reel
function estimateDelay(schedule,currentStopSequence,timestamp) {
//comparer l'heure qu'il est avec l'heure à laquelle il est supposé arriver au prochain arret, si heure courante superieure = retard
if (schedule[currentStopSequence-1])
return Math.round((timestamp - timeToUnixTimestamp(schedule[currentStopSequence-1].a))/60);
}
// Retourne le nom lisible du premier arrêt d'un trajet
function getStartPoint(tripId) {
const schedule = horairesData[tripId]; // busSchedules doit contenir les données du fichier
if (schedule)
return getStopName(schedule[0].s,stopsData) //s = stopId
else return " "
}
// Retourne le nom lisible du terminus d'un trajet
function getEndPoint(tripId) {
const schedule = horairesData[tripId]; // busSchedules doit contenir les données du fichier
if (schedule)
return getStopName(schedule[(schedule.length)-1].s,stopsData) // s = stopId
else return " "
}
// Genere l'HTML de l'horaire de ce trip avec affichage du retard
function showSchedule(tripId, startTime, currentStopSequence, nextStopId, timestamp, delay, element) {
const scheduleDiv = document.getElementById(`schedule-${tripId}`);
if (scheduleDiv.innerHTML) {
scheduleDiv.innerHTML = ""; // Masque l'horaire si déjà affiché
element.closest(".leaflet-popup").style.width = ""; // Réinitialiser la largeur
return;
}
// Simuler un chargement (optionnel)
scheduleDiv.innerHTML = "Chargement...";
// Récupérer les horaires de ce trajet a partir des donnees horaires theoriques
const schedule = horairesData[tripId]; // variable definie dans le .js chargé
if (!schedule) {
scheduleDiv.innerHTML = "<span>Aucun horaire trouvé.</span>";
return;
}
const stringdelay = delay > 0 ? '(+'+delay+')' : '';
// Construire l'affichage des horaires
let scheduleHtml = "<ul>";
//scheduleHtml += `Delta estimé: ${estimate `;
schedule.forEach(entry => {
const stopName = getStopName(entry.s,stopsData);
const isNextStop = entry.s === nextStopId;
// entry.a = arrival_time
if (isNextStop)
scheduleHtml += `<li ${isNextStop ? 'style="font-weight: bold; "' : ''}>
${entry.a.slice(0, 5)} <span style="color: red;"> ${stringdelay} </span> - ${stopName}
</li>`;
else
scheduleHtml += `<li ${isNextStop ? 'style="font-weight: bold; "' : ''}>
${entry.a.slice(0, 5)} - ${stopName}
</li>`;
});
scheduleHtml += "</ul>";
scheduleDiv.innerHTML = scheduleHtml;
// ajuster largeur popup
const popup = element.closest(".leaflet-popup");
if (popup) {
popup.style.width = Math.min(500, scheduleDiv.scrollWidth + 50) + "px";
}
}
// ---------------------------------------------------------------------------------------------
// Fonction principale pour récupérer les donnees temps reel et afficher les marqueurs des bus sur la carte
async function fetchRealTimeBusData() {
try {
// Uses external API to get real-time json data
const response = await fetch(RT_API_URL);
const data = await response.json();
// Récupère la valeur du filtre de ligne entré par l'utilisateur.ice
let filterValues = document.getElementById('busFilter').value.split(" ").map(num => num.trim()); // Convertit en tableau
// Vérifier et initialiser busMarkers correctement
if (!Array.isArray(busMarkers)) {
busMarkers = [];
}
// Supprimer les anciens marqueurs
if (busMarkers) {
busMarkers.forEach(marker => map.removeLayer(marker));
busMarkers = [];
}
data.markers.forEach(bus => {
const { vehicleId, latitude, longitude, speed, trip, stopId, currentStopSequence, timestamp } = bus;
// Appliquer le filtre (si non vide)
if (filterValues.length > 0 && filterValues[0] != '' && !filterValues.includes(trip.route_short_name.toString())) return;
const nextStopName = getStopName(bus.stopId,stopsData);
// not used anymore
//const timeSinceStart = getTimeSinceStart(bus.trip.startTime);
const startPoint = getStartPoint(bus.trip.tripId);
const endPoint = getEndPoint(bus.trip.tripId);
//Bus icon color can be either based on delay, or on bus speed.
const schedule = horairesData[bus.trip.tripId];
const delay = schedule ? estimateDelay(schedule,bus.currentStopSequence,bus.timestamp) : 0;
const busColor = getBusDelayColor(delay);
//const busColor = getBusSpeedColor(speed);
// Contenu du popup (pourrait n'être créé qu'onclick)
//<b>Ligne ${trip.route_short_name}</b> - ${trip.route_long_name} <br>
//🏁 Démarrage: ${bus.trip.startTime} (il y a ${timeSinceStart} minutes)<br>
const popupContent = `
<b>Ligne ${trip.route_short_name}</b> ${trip.route_long_name} <br>
De: ${startPoint} <br>
Vers: <i class="fas fa-arrow-right"></i> ${endPoint} <br>
<!-- 🚌 Bus ID: ${vehicleId} <br> //-->
<i class="fas fa-map-marker-alt"></i> Position: ${latitude.toFixed(5)}, ${longitude.toFixed(5)} <br>
<i class="fas fa-tachometer-alt"></i> Vitesse: ${speed ? speed + " km/h" : "N/A"} <br>
<i class="fas fa-bus"></i> Prochain arrêt: ${nextStopName} ${delay>0 ? '<span style="color:red;">+'+delay+'</span>': ""}<br>
<a href="#" onclick="showSchedule('${bus.trip.tripId}','${bus.trip.startTime}', '${bus.currentStopSequence}', '${bus.stopId}', '${bus.timestamp}', '${delay}', this)">Voir l'horaire</a>
<div id="schedule-${bus.trip.tripId}"></div>
`;
// Définition de l'icône avec couleur dynamique en fonction de la vitesse
const busIcon = L.divIcon({
html: `
<div class="bus-marker" style="border: 3px solid ${busColor};">
<i class="fas fa-bus" style="color: ${busColor};"></i>
<span class="bus-number">${bus.trip.route_short_name}</span>
</div>
`,
className: 'custom-bus-icon',
iconSize: [40, 40],
iconAnchor: [20, 20]
});
if (busMarkers[vehicleId]) {
// Mise à jour du marqueur existant // not used anymore since we delete busmarkers
busMarkers[vehicleId].setLatLng([latitude, longitude])
.setPopupContent(popupContent)
.setIcon(busIcon);
} else {
// Ajout d'un nouveau marqueur
busMarkers[vehicleId] = L.marker([latitude, longitude], { icon: busIcon}).addTo(map)
.bindTooltip(`<i class="fas fa-arrow-right"></i> ${endPoint}`, { permanent: false, direction: "top" })
.bindPopup(popupContent);
}
});
//update the number of visible bus in map view
let bounds = map.getBounds();
let visibleBuses = busMarkers.filter(marker => bounds.contains(marker.getLatLng()));
document.getElementById('busCount').textContent = visibleBuses.length;
} catch (error) {
console.error("Erreur lors du chargement des données distantes:", error);
}
}
// Rafraîchir toutes les 6 secondes
fetchRealTimeBusData();
setInterval(fetchRealTimeBusData, RT_REFRESH_RATE);
</script>
</body>
</html>