-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.js
More file actions
835 lines (699 loc) · 30.3 KB
/
app.js
File metadata and controls
835 lines (699 loc) · 30.3 KB
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
// app.js
// Bike Sensor Data Visualization
// This application visualizes bike trip data from PMTiles, including speed, road quality,
// traffic light analysis, and averaged road segments
import { CONFIG } from './config.js';
console.log('🚀 Starting bike visualization...');
// Initialize map
const map = new mapboxgl.Map({
container: 'map',
style: CONFIG.MAP_STYLE,
center: CONFIG.MAP_CENTER,
zoom: CONFIG.MAP_ZOOM
});
window.map = map; // Make map available globally for debugging
// State management
let tripLayers = []; // Array of all trip layer IDs loaded from PMTiles
let speedMode = 'gradient'; // 'gradient' or 'categories' for speed visualization
let showSpeedColors = false; // Toggle for speed color overlay
let showRoadQuality = false; // Toggle for road quality overlay
let selectedTrip = null; // Currently selected trip layer ID
let tripsMetadata = null; // Metadata object containing trip statistics
let currentPopup = null; // Reference to currently open popup
let showTrafficLights = false; // Toggle for traffic light layer visibility
let analysisMode = 'safety'; // 'safety', 'efficiency', or 'overall' for traffic light analysis
let trafficLightInfoShown = false; // Track if info popup has been shown
let showAveragedSegments = false; // Toggle for averaged road segments layer
let averagedSegmentMode = 'composite'; // 'speed', 'quality', or 'composite' for segment visualization
const DEFAULT_COLOR = '#FF6600';
// Color expressions- Returns different colors based on different scores/values
function getSpeedColorExpression(mode) {
const speedValue = ['to-number', ['coalesce', ['get', 'Speed'], ['get', 'speed'], 0]];
if (mode === 'gradient') {
return ['interpolate', ['linear'], speedValue, 0, '#808080', 2, '#DC2626', 5, '#F97316', 10, '#FACC15', 15, '#22C55E', 20, '#3B82F6', 25, '#6366F1'];
} else {
return ['step', speedValue, '#808080', 2, '#DC2626', 5, '#F97316', 10, '#FACC15', 15, '#22C55E', 20, '#3B82F6', 25, '#6366F1'];
}
}
function getRoadQualityColorExpression() {
return ['match', ['get', 'road_quality'], 1, '#22C55E', 2, '#84CC16', 3, '#FACC15', 4, '#F97316', 5, '#DC2626', '#808080'];
}
function getTrafficLightColorExpression(mode) {
const scoreKey = mode === 'safety' ? 'safety_score' : mode === 'efficiency' ? 'efficiency_score' : 'overall_score';
return ['case', ['==', ['get', 'has_data'], false], '#FFFFFF', ['step', ['to-number', ['get', scoreKey]], '#16A34A', 10, '#22C55E', 20, '#4ADE80', 30, '#84CC16', 40, '#FDE047', 50, '#FACC15', 60, '#FB923C', 70, '#F97316', 80, '#DC2626']];
}
function getAnalysisLabel(score) {
if (score < 10) return 'Excellent+';
if (score < 20) return 'Excellent';
if (score < 30) return 'Good+';
if (score < 40) return 'Good';
if (score < 50) return 'Moderate+';
if (score < 60) return 'Moderate';
if (score < 70) return 'Poor+';
if (score < 80) return 'Poor';
return 'Critical';
}
function getAveragedSpeedColorExpression() {
return ['interpolate', ['linear'], ['get', 'avg_speed'], 0, '#DC2626', 5, '#F97316', 10, '#FACC15', 15, '#22C55E', 20, '#3B82F6', 25, '#6366F1'];
}
function getAveragedQualityColorExpression() {
return ['interpolate', ['linear'], ['get', 'avg_quality'], 1, '#22C55E', 2, '#84CC16', 3, '#FACC15', 4, '#F97316', 5, '#DC2626'];
}
function getCompositeScoreColorExpression() {
return ['interpolate', ['linear'], ['get', 'composite_score'], 0, '#22C55E', 25, '#84CC16', 50, '#FACC15', 75, '#F97316', 100, '#DC2626'];
}
function getQualityLabel(quality) {
if (quality <= 1.5) return 'Perfect';
if (quality <= 2.5) return 'Normal';
if (quality <= 3.5) return 'Outdated';
if (quality <= 4.5) return 'Bad';
return 'No road';
}
function getCompositeLabel(score) {
if (score < 20) return 'Excellent';
if (score < 40) return 'Good';
if (score < 60) return 'Moderate';
if (score < 80) return 'Poor';
return 'Critical';
}
// Data loading functions
async function loadMetadata() {
const possiblePaths = [`${CONFIG.DATA_URL}/trips_metadata.json`, '/trips_metadata.json', './trips_metadata.json', 'trips_metadata.json'];
for (const path of possiblePaths) {
try {
console.log('Trying to load metadata from:', path);
const response = await fetch(path);
if (response.ok) {
tripsMetadata = await response.json();
console.log('✅ Loaded trip metadata from', path, 'for', Object.keys(tripsMetadata).length, 'trips');
return tripsMetadata;
}
} catch (err) {
console.log('❌ Failed to load from', path);
}
}
console.warn('⚠️ Could not load metadata');
return null;
}
async function loadAveragedSegments() {
const possiblePaths = ['./road_segments_averaged.json', 'road_segments_averaged.json', '/road_segments_averaged.json', `${CONFIG.DATA_URL}/road_segments_averaged.json`];
for (const path of possiblePaths) {
try {
console.log('🔍 Trying to load averaged segments from:', path);
const response = await fetch(path);
if (response.ok) {
const data = await response.json();
console.log(`✅ Loaded ${data.features.length} averaged road segments from`, path);
return data;
}
} catch (err) {
console.log('❌ Failed to load from', path);
}
}
console.error('❌ Could not load averaged segments');
return null;
}
// Statistics calculator (ie: for aggregated stats)
function getTripStats(tripId) {
if (!tripsMetadata) {
console.warn('⚠️ No metadata loaded');
return null;
}
const variations = [tripId, tripId.replace(/_clean_processed$/i, ''), tripId.replace(/_clean$/i, ''), tripId.replace(/_processed$/i, ''), tripId.replace(/_clean/gi, '').replace(/_processed/gi, ''), tripId.split('_clean')[0], tripId.split('_processed')[0]];
let tripData = null;
for (const variant of variations) {
if (tripsMetadata[variant]) {
tripData = tripsMetadata[variant];
break;
}
}
if (!tripData) return null;
const meta = tripData.metadata || tripData;
const gnssLine = meta['GNSS'];
if (!gnssLine) return null;
// Parse GNSS line (comma-separated values)
const parts = gnssLine.split(',');
return {
duration: parts[1],
stops: parts[2],
distance: parseFloat(parts[3]) || 0,
avgSpeed: parseFloat(parts[4]) || 0,
avgSpeedWOS: parseFloat(parts[5]) || 0,
maxSpeed: parseFloat(parts[6]) || 0,
elevation: parseFloat(parts[11]) || 0
};
}
function calculateAggregateStats() {
if (!tripsMetadata) return null;
let totalDistance = 0, totalTime = 0, totalAvgSpeed = 0, tripCount = 0;
Object.keys(tripsMetadata).forEach(tripId => {
const stats = getTripStats(tripId);
if (stats) {
totalDistance += stats.distance;
const [part1, part2] = stats.duration.split(':').map(Number);
totalTime += (part1 * 60 + part2) * 60;
totalAvgSpeed += stats.avgSpeed;
tripCount++;
}
});
const avgSpeed = tripCount > 0 ? (totalAvgSpeed / tripCount) : 0;
return { tripCount, totalDistance: totalDistance.toFixed(1), totalTime: formatDuration(totalTime), avgSpeed: avgSpeed.toFixed(1) };
}
function formatDuration(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
}
// Trip selection functions
function resetSelection() {
console.log('Resetting selection');
selectedTrip = null;
if (currentPopup) {
currentPopup.remove();
currentPopup = null;
}
// Reset all trip layers to default style
tripLayers.forEach(layerId => {
try {
map.setPaintProperty(layerId, 'line-opacity', 0.7);
map.setPaintProperty(layerId, 'line-width', 3);
if (showSpeedColors) {
map.setPaintProperty(layerId, 'line-color', getSpeedColorExpression(speedMode));
} else if (showRoadQuality) {
map.setPaintProperty(layerId, 'line-color', getRoadQualityColorExpression());
} else {
map.setPaintProperty(layerId, 'line-color', DEFAULT_COLOR);
}
} catch (err) {
console.error('Error resetting layer:', layerId, err);
}
});
// Reset UI
document.getElementById('resetButton').style.display = 'none';
document.getElementById('selectedTripRow').style.display = 'none';
document.getElementById('statTripRow').style.display = 'flex';
document.getElementById('statDistanceRow').style.display = 'flex';
document.getElementById('statAvgSpeedRow').style.display = 'flex';
document.getElementById('statTotalTimeRow').style.display = 'flex';
}
function showSelection(layerId) {
console.log('Showing selection for:', layerId);
document.getElementById('resetButton').style.display = 'block';
document.getElementById('statTripRow').style.display = 'none';
document.getElementById('statDistanceRow').style.display = 'none';
document.getElementById('statAvgSpeedRow').style.display = 'none';
document.getElementById('statTotalTimeRow').style.display = 'none';
document.getElementById('selectedTripRow').style.display = 'flex';
const tripName = layerId.replace(/_/g, ' ').replace(/processed/gi, '').replace(/clean/gi, '').trim();
document.getElementById('selectedTrip').textContent = tripName;
}
function searchAndHighlightTrip(searchTerm) {
if (!searchTerm) {
resetSelection();
return;
}
const normalizedSearch = searchTerm.toLowerCase().trim();
const matchingTrip = tripLayers.find(layerId => layerId.toLowerCase().includes(normalizedSearch));
if (matchingTrip) {
console.log('🎯 Found trip:', matchingTrip);
selectedTrip = matchingTrip;
// Highlight selected trip, dim others
tripLayers.forEach(id => {
try {
if (id === matchingTrip) {
map.setPaintProperty(id, 'line-opacity', 1.0);
map.setPaintProperty(id, 'line-width', 5);
map.setPaintProperty(id, 'line-color', '#FF00FF');
} else {
map.setPaintProperty(id, 'line-opacity', 0.15);
map.setPaintProperty(id, 'line-width', 2);
}
} catch (err) {
console.error('Error updating layer:', id, err);
}
});
showSelection(matchingTrip);
// Zoom to selected trip
try {
const features = map.querySourceFeatures('trips', { sourceLayer: matchingTrip });
if (features.length > 0) {
const bbox = turf.bbox({ type: 'FeatureCollection', features: features });
map.fitBounds(bbox, { padding: 50, duration: 1000 });
}
} catch (err) {
console.error('Error zooming to trip:', err);
}
return true;
} else {
console.log('❌ No trip found matching:', searchTerm);
alert(`No trip found matching: ${searchTerm}`);
return false;
}
}
// Layer update functions
function updateTrafficLightColors() {
console.log('🎨 Updating traffic light colors, mode:', analysisMode);
if (!map.getLayer('verkeerslichten')) {
console.warn('⚠️ Traffic lights layer not found');
return;
}
map.setPaintProperty('verkeerslichten', 'circle-color', getTrafficLightColorExpression(analysisMode));
console.log('✅ Traffic light colors updated');
}
function updateAveragedSegmentColors() {
if (!map.getLayer('averaged-segments')) return;
let colorExpression;
switch (averagedSegmentMode) {
case 'speed': colorExpression = getAveragedSpeedColorExpression(); break;
case 'quality': colorExpression = getAveragedQualityColorExpression(); break;
case 'composite': colorExpression = getCompositeScoreColorExpression(); break;
}
map.setPaintProperty('averaged-segments', 'line-color', colorExpression);
console.log('🎨 Updated averaged segment colors to:', averagedSegmentMode);
}
// Map layer setup
async function setupAveragedSegments() {
console.log('📡 Loading averaged road segments...');
const segmentsData = await loadAveragedSegments();
if (!segmentsData) {
console.error('❌ Could not load averaged segments');
return;
}
// Add GeoJSON source
map.addSource('averaged-segments', { type: 'geojson', data: segmentsData });
// Add line layer (initially hidden)
map.addLayer({
id: 'averaged-segments',
type: 'line',
source: 'averaged-segments',
layout: { 'visibility': 'none', 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': getCompositeScoreColorExpression(),
'line-width': ['interpolate', ['linear'], ['zoom'], 10, 2, 14, 4, 16, 6],
'line-opacity': 0.8
}
});
console.log('✅ Averaged segments layer added');
// Click handler to show segment details
map.on('click', 'averaged-segments', (e) => {
e.preventDefault();
if (e.originalEvent) e.originalEvent.stopPropagation();
const props = e.features[0].properties;
let qualityText = props.avg_quality ? `🛣️ Avg Quality: ${props.avg_quality} (${getQualityLabel(props.avg_quality)})` : '🛣️ Quality: No data';
let compositeText = getCompositeLabel(props.composite_score);
new mapboxgl.Popup().setLngLat(e.lngLat).setHTML(`
<strong>📊 Averaged Road Segment</strong><br>
🚴 Avg Speed: ${props.avg_speed} km/h<br>
📈 Speed Range: ${props.min_speed} - ${props.max_speed} km/h<br>
${qualityText}<br>
📏 Distance: ${props.distance_m}m<br>
🎯 Composite Score: ${props.composite_score} (${compositeText})<br>
📍 Observations: ${props.observation_count}<br>
🚲 From ${props.trip_count} trips
`).addTo(map);
});
// Cursor changes
map.on('mouseenter', 'averaged-segments', () => { map.getCanvas().style.cursor = 'pointer'; });
map.on('mouseleave', 'averaged-segments', () => { map.getCanvas().style.cursor = ''; });
}
// Map event handlers (ie: initializing all data and layers)
map.on('error', (e) => { console.error('❌ Map error:', e); });
map.on('load', async () => {
console.log('✅ Map loaded');
await loadMetadata();
try {
console.log('📡 Loading bike trips from:', CONFIG.PMTILES_URL);
// Setup PMTiles protocol
const protocol = new pmtiles.Protocol();
mapboxgl.addProtocol('pmtiles', protocol.tile);
const pmtilesUrl = CONFIG.PMTILES_URL;
const p = new pmtiles.PMTiles(pmtilesUrl);
protocol.add(p);
const metadata = await p.getMetadata();
console.log('✅ PMTiles loaded:', metadata);
const layers = metadata.vector_layers || [];
tripLayers = layers.map(l => l.id);
console.log('📊 Found', tripLayers.length, 'trips');
// Add trips source
map.addSource('trips', { type: 'vector', url: `pmtiles://${pmtilesUrl}`, attribution: 'Bike sensor data' });
// Add a layer for each trip
tripLayers.forEach(layerId => {
map.addLayer({
id: layerId,
type: 'line',
source: 'trips',
'source-layer': layerId,
paint: { 'line-color': DEFAULT_COLOR, 'line-width': 3, 'line-opacity': 0.7 }
});
});
console.log('✅ All trips loaded and visible');
// Load traffic lights with pre-computed analysis
console.log('📡 Loading traffic light analysis...');
try {
const possiblePaths = ['./traffic_lights_analyzed.json', 'traffic_lights_analyzed.json', '/traffic_lights_analyzed.json', `${CONFIG.DATA_URL}/traffic_lights_analyzed.json`];
let trafficLightsData = null;
for (const path of possiblePaths) {
try {
console.log('🔍 Trying to load from:', path);
const response = await fetch(path);
if (response.ok) {
trafficLightsData = await response.json();
console.log('✅ Loaded analyzed traffic lights from', path);
console.log(`📍 Found ${trafficLightsData.features.length} traffic lights with analysis`);
break;
}
} catch (err) {
console.log('❌ Failed to load from', path, err.message);
}
}
if (!trafficLightsData) {
console.error('❌ Could not load traffic light analysis');
} else {
// Add traffic lights source and layer
map.addSource('verkeerslichten', { type: 'geojson', data: trafficLightsData });
map.addLayer({
id: 'verkeerslichten',
type: 'circle',
source: 'verkeerslichten',
layout: { 'visibility': 'none' },
paint: {
'circle-radius': 6,
'circle-color': getTrafficLightColorExpression('safety'),
'circle-stroke-width': 2,
'circle-stroke-color': '#333333',
'circle-opacity': 0.9
}
});
console.log('✅ Traffic lights layer added');
// Click handler for traffic lights
map.on('click', 'verkeerslichten', (e) => {
e.preventDefault();
if (e.originalEvent) e.originalEvent.stopPropagation();
const props = e.features[0].properties;
console.log('🚦 Clicked traffic light:', props);
let analysisHTML = '';
if (props.has_data === 'true' || props.has_data === true) {
const safetyScore = parseFloat(props.safety_score || 0);
const efficiencyScore = parseFloat(props.efficiency_score || 0);
const overallScore = parseFloat(props.overall_score || 0);
const suddenBrakes = parseInt(props.sudden_brakes || 0);
const extendedStops = parseInt(props.extended_stops || 0);
const totalPoints = parseInt(props.total_points || 0);
let displayScore = analysisMode === 'safety' ? safetyScore : analysisMode === 'efficiency' ? efficiencyScore : overallScore;
const displayLabel = getAnalysisLabel(displayScore);
const displayColor = displayScore < 20 ? '#22C55E' : displayScore < 40 ? '#84CC16' : displayScore < 60 ? '#FACC15' : displayScore < 80 ? '#F97316' : '#DC2626';
analysisHTML = `
<br><br><strong>📊 Traffic Light Analysis:</strong>
<br>🛑 Sudden braking events: ${suddenBrakes}
<br>⏱️ Extended stop points: ${extendedStops}
<br>📍 Total points checked: ${totalPoints}
<br>📈 Safety score: ${safetyScore.toFixed(0)}/100
<br>🕐 Efficiency score: ${efficiencyScore.toFixed(0)}/100
<br>🎯 Overall score: ${overallScore.toFixed(0)}/100
<br><br><strong>Current View (${analysisMode}):</strong>
<br><span style="color: ${displayColor}; font-size: 20px;">●</span> <strong>${displayLabel}</strong> (Score: ${displayScore.toFixed(0)})
`;
} else {
analysisHTML = '<br><br><em>No trip data near this traffic light</em>';
}
new mapboxgl.Popup().setLngLat(e.lngLat).setHTML(`<strong>🚦 Verkeerslicht</strong><br>${props.Kruispunt || 'Geen locatie beschikbaar'}${analysisHTML}`).addTo(map);
});
map.on('mouseenter', 'verkeerslichten', () => { map.getCanvas().style.cursor = 'pointer'; });
map.on('mouseleave', 'verkeerslichten', () => { map.getCanvas().style.cursor = ''; });
}
} catch (err) {
console.error('❌ Error loading traffic lights:', err);
}
await setupAveragedSegments();
map.setCenter([4.9041, 52.3676]);
map.setZoom(13);
setupControls();
setupClickHandlers();
updateStatsFromMetadata();
} catch (err) {
console.error('❌ Error loading trips:', err);
}
});
function updateLegendPositions() {
const legends = [
{ id: 'speedLegend', el: document.getElementById('speedLegend') },
{ id: 'roadQualityLegend', el: document.getElementById('roadQualityLegend') },
{ id: 'trafficLightLegend', el: document.getElementById('trafficLightLegend') },
{ id: 'averagedSegmentsLegend', el: document.getElementById('averagedSegmentsLegend') }
].filter(legend => legend.el && legend.el.style.display === 'block');
// Position from right to left, accounting for each legend's width
let cumulativeOffset = 10;
legends.forEach((legend, index) => {
legend.el.style.right = `${cumulativeOffset}px`;
const legendWidth = legend.el.offsetWidth || 220;
cumulativeOffset += legendWidth + 10;
});
}
function setupAveragedSegmentControls() {
const avgSegmentsCheckbox = document.getElementById('averagedSegmentsCheckbox');
if (avgSegmentsCheckbox) {
avgSegmentsCheckbox.addEventListener('change', (e) => {
showAveragedSegments = e.target.checked;
const avgModeGroup = document.getElementById('averagedModeGroup');
const avgLegend = document.getElementById('averagedSegmentsLegend');
if (showAveragedSegments) {
if (map.getLayer('averaged-segments')) map.setLayoutProperty('averaged-segments', 'visibility', 'visible');
if (avgModeGroup) avgModeGroup.style.display = 'flex';
if (avgLegend) avgLegend.style.display = 'block';
updateAveragedSegmentColors();
tripLayers.forEach(layerId => { map.setLayoutProperty(layerId, 'visibility', 'none'); });
console.log('📊 Averaged segments ON');
} else {
if (map.getLayer('averaged-segments')) map.setLayoutProperty('averaged-segments', 'visibility', 'none');
if (avgModeGroup) avgModeGroup.style.display = 'none';
if (avgLegend) avgLegend.style.display = 'none';
tripLayers.forEach(layerId => { map.setLayoutProperty(layerId, 'visibility', 'visible'); });
console.log('📊 Averaged segments OFF');
}
setTimeout(updateLegendPositions, 10);
});
}
document.querySelectorAll('input[name="averagedMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
averagedSegmentMode = e.target.value;
if (showAveragedSegments) updateAveragedSegmentColors();
});
});
}
function setupControls() {
const resetButton = document.getElementById('resetButton');
if (resetButton) resetButton.addEventListener('click', () => { resetSelection(); });
const searchInput = document.getElementById('tripSearchInput');
const searchButton = document.getElementById('tripSearchButton');
if (searchInput && searchButton) {
searchButton.addEventListener('click', () => { searchAndHighlightTrip(searchInput.value); });
searchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') searchAndHighlightTrip(searchInput.value); });
}
const speedColorsCheckbox = document.getElementById('speedColorsCheckbox');
if (speedColorsCheckbox) {
speedColorsCheckbox.addEventListener('change', (e) => {
showSpeedColors = e.target.checked;
console.log('Speed colors toggled:', showSpeedColors);
if (showSpeedColors && showRoadQuality) {
showRoadQuality = false;
document.getElementById('roadQualityCheckbox').checked = false;
document.getElementById('roadQualityLegend').style.display = 'none';
}
const speedLegend = document.getElementById('speedLegend');
const speedModeGroup = document.getElementById('speedModeGroup');
if (showSpeedColors) {
const colorExpression = getSpeedColorExpression(speedMode);
tripLayers.forEach(layerId => { map.setPaintProperty(layerId, 'line-color', colorExpression); });
speedLegend.style.display = 'block';
speedModeGroup.style.display = 'flex';
} else {
tripLayers.forEach(layerId => { map.setPaintProperty(layerId, 'line-color', DEFAULT_COLOR); });
speedLegend.style.display = 'none';
speedModeGroup.style.display = 'none';
}
setTimeout(updateLegendPositions, 10);
});
}
const roadQualityCheckbox = document.getElementById('roadQualityCheckbox');
if (roadQualityCheckbox) {
roadQualityCheckbox.addEventListener('change', (e) => {
showRoadQuality = e.target.checked;
console.log('Road quality toggled:', showRoadQuality);
if (showRoadQuality && showSpeedColors) {
showSpeedColors = false;
document.getElementById('speedColorsCheckbox').checked = false;
document.getElementById('speedLegend').style.display = 'none';
document.getElementById('speedModeGroup').style.display = 'none';
}
const roadQualityLegend = document.getElementById('roadQualityLegend');
if (showRoadQuality) {
const colorExpression = getRoadQualityColorExpression();
tripLayers.forEach(layerId => {
map.setPaintProperty(layerId, 'line-color', colorExpression);
});
roadQualityLegend.style.display = 'block';
} else {
tripLayers.forEach(layerId => {
map.setPaintProperty(layerId, 'line-color', DEFAULT_COLOR);
});
roadQualityLegend.style.display = 'none';
}
updateLegendPositions();
});
}
document.querySelectorAll('input[name="speedMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
speedMode = e.target.value;
if (showSpeedColors) {
tripLayers.forEach(layerId => {
map.setPaintProperty(layerId, 'line-color', getSpeedColorExpression(speedMode));
});
}
});
});
const trafficLightsCheckbox = document.getElementById('trafficLightsCheckbox');
if (trafficLightsCheckbox) {
trafficLightsCheckbox.addEventListener('change', (e) => {
showTrafficLights = e.target.checked;
const analysisModeGroup = document.getElementById('analysisModeGroup');
const analysisLegend = document.getElementById('trafficLightLegend');
if (showTrafficLights) {
if (map.getLayer('verkeerslichten')) {
map.setLayoutProperty('verkeerslichten', 'visibility', 'visible');
}
if (analysisModeGroup) analysisModeGroup.style.display = 'flex';
if (analysisLegend) analysisLegend.style.display = 'block';
updateTrafficLightColors();
if (!trafficLightInfoShown) {
showTrafficLightInfoPopup();
trafficLightInfoShown = true;
}
console.log('🚦 Traffic lights analysis ON');
}
else {
if (map.getLayer('verkeerslichten')) {
map.setLayoutProperty('verkeerslichten', 'visibility', 'none');
}
if (analysisModeGroup) analysisModeGroup.style.display = 'none';
if (analysisLegend) analysisLegend.style.display = 'none';
console.log('🚦 Traffic lights OFF');
}
updateLegendPositions();
});
}
document.querySelectorAll('input[name="analysisMode"]').forEach(radio => {
radio.addEventListener('change', (e) => {
analysisMode = e.target.value;
if (showTrafficLights) {
updateTrafficLightColors();
}
});
});
// Setup averaged segment controls
setupAveragedSegmentControls();
}
function setupClickHandlers() {
tripLayers.forEach(layerId => {
map.on('click', layerId, async (e) => {
if (showTrafficLights) {
return;
}
console.log('Layer clicked:', layerId);
e.preventDefault();
if (e.originalEvent) {
e.originalEvent.stopPropagation();
}
if (currentPopup) {
currentPopup.remove();
}
const props = e.features[0].properties;
const speed = parseFloat(props.Speed || props.speed || 0);
const roadQuality = parseInt(props.road_quality || props.roadQuality || 0);
selectedTrip = layerId;
tripLayers.forEach(id => {
try {
if (id === layerId) {
map.setPaintProperty(id, 'line-opacity', 1.0);
map.setPaintProperty(id, 'line-width', 4);
} else {
map.setPaintProperty(id, 'line-opacity', 0.15);
map.setPaintProperty(id, 'line-width', 2);
}
} catch (err) {
console.error('Error updating layer:', id, err);
}
});
showSelection(layerId);
const stats = getTripStats(layerId);
let distanceKm, avgSpeed, maxSpeed, durationFormatted;
if (stats) {
distanceKm = stats.distance.toFixed(2);
avgSpeed = stats.avgSpeed.toFixed(1);
maxSpeed = stats.maxSpeed.toFixed(1);
durationFormatted = stats.duration;
} else {
distanceKm = '—';
avgSpeed = '—';
maxSpeed = '—';
durationFormatted = '—';
}
const qualityLabels = {
1: 'Perfect',
2: 'Normal',
3: 'Outdated',
4: 'Bad',
5: 'No road',
0: 'Unknown'
};
const qualityLabel = qualityLabels[roadQuality] || 'Unknown';
const popupTripName = layerId.replace(/_/g, ' ').replace(/processed/gi, '').replace(/clean/gi, '').trim();
currentPopup = new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(`
<strong>${popupTripName}</strong><br>
🚴 Speed at point: ${speed} km/h<br>
🛣️ Road quality: ${roadQuality} (${qualityLabel})<br>
📊 Average speed: ${avgSpeed} km/h<br>
🏁 Max speed: ${maxSpeed} km/h<br>
📍 Total distance: ${distanceKm} km<br>
⏱️ Duration: ${durationFormatted}
`)
.addTo(map);
});
map.on('mouseenter', layerId, () => {
if (!showTrafficLights) {
map.getCanvas().style.cursor = 'pointer';
}
});
map.on('mouseleave', layerId, () => {
map.getCanvas().style.cursor = '';
});
});
// Click anywhere on map to deselect trip
map.on('click', (e) => {
if (!e.defaultPrevented && selectedTrip && !showTrafficLights) {
resetSelection();
}
});
}
function updateStatsFromMetadata() {
// Always show the actual number of loaded trips first
const actualTripCount = tripLayers.length;
document.getElementById('statTrips').textContent = actualTripCount;
if (!tripsMetadata) {
console.warn('⚠️ No metadata loaded, showing trip count only');
return;
}
const aggregateStats = calculateAggregateStats();
if (aggregateStats) {
// Use actual loaded trip count, not metadata count
document.getElementById('statTrips').textContent = actualTripCount;
document.getElementById('statDistance').textContent = `${aggregateStats.totalDistance} km`;
document.getElementById('statAvgSpeed').textContent = `${aggregateStats.avgSpeed} km/h`;
document.getElementById('statTotalTime').textContent = aggregateStats.totalTime;
console.log('✅ Stats updated from metadata:', aggregateStats);
console.log(`📊 Actual trips loaded: ${actualTripCount}, Metadata trips: ${aggregateStats.tripCount}`);
}
}
// Make search function available globally for console testing
window.searchTrip = searchAndHighlightTrip;