-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
773 lines (681 loc) · 26.2 KB
/
Copy pathindex.html
File metadata and controls
773 lines (681 loc) · 26.2 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
<!DOCTYPE html>
<html>
<head>
<title>mapspeed + Route Simulator</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; }
body { font-family: "Inter", "Segoe UI", system-ui, -apple-system, sans-serif; background: #0b1220; color: #111827; }
#app { position: relative; width: 100%; height: 100%; }
#map { width: 100%; height: 100%; }
.panel {
position: absolute;
z-index: 1000;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(229, 231, 235, 0.8);
border-radius: 12px;
box-shadow: 0 10px 20px rgba(0,0,0,0.12);
backdrop-filter: blur(6px);
padding: 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.panel.top-left { top: 14px; left: 14px; width: 320px; }
.panel-title { font-weight: 700; font-size: 14px; color: #0f172a; }
.panel-hint { font-size: 12px; color: #475569; }
.panel-actions { display: flex; gap: 8px; }
.route-info {
padding: 8px 10px;
background: #ecfdf5;
border: 1px solid #d1fae5;
color: #065f46;
border-radius: 8px;
font-size: 12px;
}
.speed-limit {
width: 54px;
height: 54px;
border-radius: 50%;
background: #ffffff;
border: 4px solid #ef4444;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 16px;
color: #111827;
box-shadow: 0 6px 14px rgba(0,0,0,0.15);
}
.speed-limit-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
.speed-limit-label {
font-size: 11px;
color: #475569;
text-transform: uppercase;
letter-spacing: 0.04em;
font-weight: 700;
}
.ghost-btn {
background: rgba(30, 41, 59, 0.9);
color: #f1f5f9;
border: 1px solid rgba(100, 116, 139, 0.6);
border-radius: 999px;
padding: 6px 14px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
}
.ghost-btn:hover { background: rgba(51, 65, 85, 0.95); }
.ghost-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.primary-btn {
padding: 8px 14px;
background: #0ea5e9;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
font-size: 12px;
}
.primary-btn:hover { background: #0284c7; }
.info-panel {
position: absolute;
bottom: 14px;
left: 14px;
right: 14px;
z-index: 1000;
display: flex;
gap: 14px;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(229, 231, 235, 0.8);
border-radius: 12px;
backdrop-filter: blur(6px);
font-size: 12px;
flex-wrap: wrap;
}
.info-item { display: flex; flex-direction: column; gap: 2px; }
.info-label { color: #64748b; font-weight: 700; font-size: 10px; text-transform: uppercase; }
.info-value { color: #0f172a; font-weight: 700; font-size: 12px; }
.loading {
position: absolute;
top: 14px;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
background: rgba(255, 255, 255, 0.95);
border: 1px solid #e5e7eb;
padding: 8px 16px;
border-radius: 999px;
box-shadow: 0 8px 16px rgba(0,0,0,0.12);
font-weight: 600;
font-size: 12px;
display: none;
}
.hover-tooltip {
position: absolute;
z-index: 1001;
background: rgba(15, 23, 42, 0.9);
color: #f1f5f9;
padding: 6px 10px;
border-radius: 6px;
font-size: 12px;
font-weight: 600;
pointer-events: none;
display: none;
white-space: nowrap;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}
.hover-tooltip .speed-value {
font-size: 14px;
font-weight: 700;
}
</style>
</head>
<body>
<div id="app">
<div id="map"></div>
<div id="loading" class="loading">Loading road speeds…</div>
<div id="hover-tooltip" class="hover-tooltip"></div>
<div class="panel top-left">
<div class="panel-title">Mapspeed + Route Simulator</div>
<div class="panel-actions">
<button id="reset-btn" class="primary-btn" onclick="resetRoute()">Reset Route</button>
<button id="reload-btn" class="ghost-btn" onclick="reloadRoads()" title="Refetch road speeds for the current view">Reload</button>
<button id="toggle-btn" class="ghost-btn" onclick="togglePause()" disabled>Pause</button>
</div>
<div id="road-status" class="panel-hint">Road speeds loading…</div>
<div id="route-hint" class="panel-hint">Click the map to set a start location.</div>
<div class="speed-limit-wrapper">
<div class="speed-limit" id="speed-limit">—</div>
<div class="speed-limit-label">Speed Limit</div>
</div>
<div id="route-info" class="route-info" style="display: none;">Route loaded</div>
</div>
<div class="info-panel">
<div class="info-item">
<span class="info-label">Distance</span>
<span class="info-value" id="distance">—</span>
</div>
<div class="info-item">
<span class="info-label">Speed</span>
<span class="info-value" id="speed">— mph</span>
</div>
<div class="info-item">
<span class="info-label">ETA</span>
<span class="info-value" id="eta">—</span>
</div>
<div class="info-item">
<span class="info-label">Progress</span>
<span class="info-value" id="progress">0%</span>
</div>
<div class="info-item">
<span class="info-label">Dwell</span>
<span class="info-value" id="dwell">—</span>
</div>
</div>
</div>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="route-simulator.js"></script>
<script>
// ========================================
// Map Initialization
// ========================================
const map = L.map('map').setView([41.325, -74.165], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 19
}).addTo(map);
// ========================================
// DOM Element References
// ========================================
const loadingEl = document.getElementById('loading');
const roadStatusEl = document.getElementById('road-status');
const routeHintEl = document.getElementById('route-hint');
const routeInfoEl = document.getElementById('route-info');
const toggleBtnEl = document.getElementById('toggle-btn');
const dwellEl = document.getElementById('dwell');
const speedLimitEl = document.getElementById('speed-limit');
const hoverTooltip = document.getElementById('hover-tooltip');
// ========================================
// Speed Limit Configuration
// ========================================
const speedColorMap = {
5: '#8B0000', 10: '#DC143C', 15: '#FF0000', 20: '#FF4500',
25: '#FF6347', 30: '#FFA500', 35: '#FFD700', 40: '#FFFF00',
45: '#ADFF2F', 50: '#7FFF00', 55: '#00FF00', 60: '#00FA9A',
65: '#00CED1', 70: '#1E90FF', 75: '#0000FF'
};
const inferredSpeedByHighway = {
motorway: 65,
motorway_link: 55,
trunk: 60,
trunk_link: 50,
primary: 55,
primary_link: 45,
secondary: 45,
secondary_link: 35,
tertiary: 35,
tertiary_link: 30,
residential: 25,
unclassified: 25,
living_street: 15,
service: 15
};
function getSpeedColor(speed) {
if (!speed) return '#808080';
const speeds = Object.keys(speedColorMap).map(Number).sort((a, b) => a - b);
for (let i = speeds.length - 1; i >= 0; i--) {
if (speed >= speeds[i]) return speedColorMap[speeds[i]];
}
return speedColorMap[5];
}
function showLoading(show) {
loadingEl.style.display = show ? 'block' : 'none';
}
// ========================================
// Road Data Loading (Overpass API)
// ========================================
const roadLayerGroup = L.layerGroup().addTo(map);
// Create custom pane for route with higher z-index (above roads)
map.createPane('routePane');
map.getPane('routePane').style.zIndex = 450;
let routeOutline = null;
let roadSpeedPoints = [];
// Coverage cache: areas already fetched and the way ids drawn, so
// panning/zooming inside loaded territory skips the Overpass call
let loadedAreas = [];
let loadedWayIds = new Set();
let totalRoadCount = 0;
let totalInferredCount = 0;
// Way-identity speed data: OSM edge (node pair) -> speed, node id -> speed.
// Accumulated across viewport loads so route segments outside the current
// view keep their data.
const edgeSpeedMap = new Map();
const nodeSpeedMap = new Map();
// OSM node ids along the current route (from OSRM annotations)
let routeNodeIds = [];
let routeSpeedResolved = [];
function edgeKey(a, b) {
return a < b ? `${a}:${b}` : `${b}:${a}`;
}
const overpassEndpoints = [
'https://overpass-api.de/api/interpreter',
'https://overpass.kumi.systems/api/interpreter'
];
let roadRequestId = 0;
async function fetchOverpass(query) {
let lastError = null;
for (const endpoint of overpassEndpoints) {
try {
// Abort slow endpoints so a hung server can't stall the fallback chain
const response = await fetch(`${endpoint}?data=${encodeURIComponent(query)}`, {
signal: AbortSignal.timeout(15000)
});
if (!response.ok) throw new Error(`Overpass error ${response.status}`);
return await response.json();
} catch (err) {
lastError = err;
}
}
throw lastError || new Error('Overpass request failed');
}
async function loadRoads(force = false) {
// Cap accumulated data so long exploration sessions don't bloat memory
if (loadedWayIds.size > 25000) {
roadLayerGroup.clearLayers();
roadSpeedPoints = [];
loadedAreas = [];
loadedWayIds.clear();
totalRoadCount = 0;
totalInferredCount = 0;
}
// Skip the fetch entirely when the view is inside already-loaded territory
if (!force && loadedAreas.some(area => area.contains(map.getBounds()))) return;
const currentId = ++roadRequestId;
showLoading(true);
roadStatusEl.textContent = 'Road speeds loading…';
// Fetch with padding so small pans stay within the covered area
const bounds = map.getBounds().pad(0.2);
const bbox = `${bounds.getSouth()},${bounds.getWest()},${bounds.getNorth()},${bounds.getEast()}`;
// Only vehicular roads; footpaths and trails have no speed limit and
// bloat the response
const query = `[out:json][timeout:15];way["highway"]["highway"!~"footway|cycleway|path|steps|pedestrian|track|bridleway|corridor|platform|construction|proposed|abandoned|raceway"](${bbox});out geom;`;
try {
const data = await fetchOverpass(query);
if (currentId !== roadRequestId) return;
data.elements.forEach(way => {
if (!loadedWayIds.has(way.id) && way.geometry && way.geometry.length > 1) {
loadedWayIds.add(way.id);
const coords = way.geometry.map(pt => [pt.lat, pt.lon]);
const maxspeed = way.tags?.maxspeed;
const highwayType = way.tags?.highway;
const parsedMax = maxspeed ? parseInt(maxspeed.replace(/[^0-9]/g, ''), 10) : null;
const inferred = parsedMax || inferredSpeedByHighway[highwayType] || null;
const isInferred = !parsedMax && !!inferred;
const polyline = L.polyline(coords, {
color: getSpeedColor(inferred),
weight: isInferred ? 3 : 4,
opacity: isInferred ? 0.55 : 0.8,
dashArray: isInferred ? '6 6' : null,
interactive: false
}).bindPopup(`Road: ${way.tags?.name || 'Unnamed'}<br>Speed: ${parsedMax ? maxspeed : (inferred ? `${inferred} mph (inferred)` : 'Unknown')}`);
roadLayerGroup.addLayer(polyline);
totalRoadCount++;
if (isInferred) totalInferredCount++;
// Index this way's speed by its OSM node ids so route speeds can
// be resolved by way identity instead of 2D proximity.
if (inferred && Array.isArray(way.nodes)) {
for (let i = 0; i < way.nodes.length - 1; i++) {
const key = edgeKey(way.nodes[i], way.nodes[i + 1]);
if (!isInferred || !edgeSpeedMap.has(key)) {
edgeSpeedMap.set(key, inferred);
}
}
for (const nodeId of way.nodes) {
if (!nodeSpeedMap.has(nodeId)) nodeSpeedMap.set(nodeId, inferred);
}
}
const sampleStep = 3;
for (let i = 0; i < coords.length; i += sampleStep) {
const [lat, lon] = coords[i];
if (inferred) roadSpeedPoints.push({ lat, lon, speed: inferred });
}
}
});
loadedAreas.push(bounds);
roadStatusEl.textContent = totalRoadCount > 0
? `Road speeds loaded: ${totalRoadCount} (inferred: ${totalInferredCount})`
: 'No speed-tagged roads found in view.';
// Newly loaded ways may cover route segments that were unresolved
refreshRouteSpeedLimits();
} catch (err) {
console.error('Error loading roads:', err);
let reason;
if (err?.name === 'TimeoutError') {
reason = 'servers took longer than 15s';
} else if (/Overpass error (\d+)/.test(err?.message)) {
reason = `server returned HTTP ${err.message.match(/(\d+)/)[1]}, likely overloaded`;
} else {
reason = err?.message || 'network error';
}
roadStatusEl.textContent = `Road speeds failed to load: ${reason}. Both Overpass servers were tried; click Reload to retry.`;
} finally {
if (currentId === roadRequestId) showLoading(false);
}
}
function reloadRoads() {
clearTimeout(roadLoadTimer);
loadRoads(true);
}
let roadLoadTimer = null;
map.on('moveend', () => {
clearTimeout(roadLoadTimer);
roadLoadTimer = setTimeout(() => loadRoads(), 300);
});
// Wrap so Leaflet's event object isn't passed as the force flag
map.whenReady(() => loadRoads());
// ========================================
// Route Planning State
// ========================================
let startMarker = null;
let endMarker = null;
let vehicleMarker = null;
let routePolyline = null;
let simulator = null;
let routeUpdateInterval = null;
let isPaused = false;
let planningState = 'start';
let startLatLon = null;
let endLatLon = null;
function setHint(text) {
routeHintEl.textContent = text;
}
function clearRouteGraphics() {
startMarker?.remove();
endMarker?.remove();
routePolyline?.remove();
routeOutline?.remove();
vehicleMarker?.remove();
startMarker = null;
endMarker = null;
routePolyline = null;
routeOutline = null;
vehicleMarker = null;
}
async function handleMapClick(e) {
if (planningState === 'start') {
resetRoute(false);
startLatLon = [e.latlng.lat, e.latlng.lng];
startMarker = L.circleMarker(startLatLon, {
radius: 6,
fillColor: '#22c55e',
color: '#16a34a',
weight: 2,
opacity: 1,
fillOpacity: 0.9
}).addTo(map);
planningState = 'end';
setHint('Click the map to set an end location.');
return;
}
if (planningState === 'end') {
endLatLon = [e.latlng.lat, e.latlng.lng];
endMarker = L.circleMarker(endLatLon, {
radius: 6,
fillColor: '#ef4444',
color: '#dc2626',
weight: 2,
opacity: 1,
fillOpacity: 0.9
}).addTo(map);
planningState = 'locked';
setHint('Fetching route...');
const success = await fetchAndDisplayRoute(startLatLon, endLatLon);
if (!success) {
planningState = 'start';
setHint('Click the map to set a start location.');
return;
}
startSimulation();
setHint('Route running. Click Reset Route to plan again.');
}
}
map.on('click', handleMapClick);
function distanceSquaredMeters(lat1, lon1, lat2, lon2) {
const latScale = 111111;
const lonScale = 111111 * Math.cos((lat1 * Math.PI) / 180);
const dx = (lon2 - lon1) * lonScale;
const dy = (lat2 - lat1) * latScale;
return dx * dx + dy * dy;
}
function getNearestRoadSpeed(lat, lon) {
if (!roadSpeedPoints.length) return null;
let bestSpeed = null;
let bestDist = Infinity;
for (const point of roadSpeedPoints) {
const dist = distanceSquaredMeters(lat, lon, point.lat, point.lon);
if (dist < bestDist) {
bestDist = dist;
bestSpeed = point.speed;
}
}
const maxDistMeters = 120;
return bestDist <= maxDistMeters * maxDistMeters ? bestSpeed : null;
}
/**
* Speed for a route coordinate, resolved by way identity: look up the
* OSM edge the route traverses at that coordinate. Stacked roads
* (overpasses) can't collide because only the routed way's nodes match.
*/
function speedForRouteCoordinate(coordIdx, coordCount) {
if (!routeNodeIds.length) return null;
const lastNodeIdx = routeNodeIds.length - 1;
// Annotation nodes align 1:1 with geometry coordinates; fall back to
// proportional mapping if the counts ever disagree.
let nodeIdx;
if (routeNodeIds.length === coordCount) {
nodeIdx = coordIdx;
} else {
nodeIdx = coordCount > 1
? Math.min(lastNodeIdx, Math.round((coordIdx * lastNodeIdx) / (coordCount - 1)))
: 0;
}
// Edge leaving this node, then edge arriving at it
if (nodeIdx < lastNodeIdx) {
const speed = edgeSpeedMap.get(edgeKey(routeNodeIds[nodeIdx], routeNodeIds[nodeIdx + 1]));
if (speed) return speed;
}
if (nodeIdx > 0) {
const speed = edgeSpeedMap.get(edgeKey(routeNodeIds[nodeIdx - 1], routeNodeIds[nodeIdx]));
if (speed) return speed;
}
return nodeSpeedMap.get(routeNodeIds[nodeIdx]) || null;
}
/**
* (Re)compute the simulator's per-waypoint speed limits from way-identity
* data. Unresolved waypoints inherit the last known speed (or 30 mph) and
* are retried whenever more road data loads.
*/
function refreshRouteSpeedLimits() {
if (!simulator || !routeNodeIds.length) return;
const coordCount = simulator.waypoints.length;
for (let i = 0; i < coordCount; i++) {
if (routeSpeedResolved[i]) continue;
const speed = speedForRouteCoordinate(i, coordCount);
if (speed) {
simulator.speedLimits[i] = speed;
routeSpeedResolved[i] = true;
}
}
let lastKnown = null;
for (let i = 0; i < coordCount; i++) {
if (routeSpeedResolved[i]) {
lastKnown = simulator.speedLimits[i];
} else {
simulator.speedLimits[i] = lastKnown || 30;
}
}
}
// Hover tooltip for road speed
map.on('mousemove', (e) => {
const speed = getNearestRoadSpeed(e.latlng.lat, e.latlng.lng);
if (speed) {
hoverTooltip.innerHTML = `<span class="speed-value">${speed}</span> mph`;
hoverTooltip.style.display = 'block';
hoverTooltip.style.left = (e.containerPoint.x + 15) + 'px';
hoverTooltip.style.top = (e.containerPoint.y - 10) + 'px';
} else {
hoverTooltip.style.display = 'none';
}
});
map.on('mouseout', () => {
hoverTooltip.style.display = 'none';
});
async function fetchAndDisplayRoute(start, end) {
try {
const url = `https://router.project-osrm.org/route/v1/driving/${start[1]},${start[0]};${end[1]},${end[0]}?overview=full&geometries=geojson&annotations=nodes`;
const response = await fetch(url);
const data = await response.json();
if (!data.routes || data.routes.length === 0) {
alert('No route found');
return false;
}
const route = data.routes[0];
const coordinates = route.geometry.coordinates.map(c => [c[1], c[0]]);
routePolyline?.remove();
routeOutline?.remove();
// White outline for contrast
routeOutline = L.polyline(coordinates, {
color: '#ffffff',
weight: 8,
opacity: 0.7,
interactive: false,
pane: 'routePane'
}).addTo(map);
// Dark purple route line
routePolyline = L.polyline(coordinates, {
color: '#581c87',
weight: 5,
opacity: 0.75,
interactive: false,
pane: 'routePane'
}).addTo(map);
map.fitBounds(routePolyline.getBounds().pad(0.1));
const totalDistMeters = route.distance;
const totalDistMiles = totalDistMeters * 0.000621371;
// OSM node ids the route traverses. Each leg's annotation has one
// node per leg coordinate; legs share their boundary coordinate, so
// trim only the first node of subsequent legs to keep the node list
// aligned 1:1 with the route geometry.
routeNodeIds = [];
for (const leg of route.legs || []) {
const legNodes = leg.annotation?.nodes || [];
const startIdx = routeNodeIds.length &&
routeNodeIds[routeNodeIds.length - 1] === legNodes[0] ? 1 : 0;
routeNodeIds.push(...legNodes.slice(startIdx));
}
routeSpeedResolved = new Array(coordinates.length).fill(false);
simulator = new RouteSimulator(coordinates, new Array(coordinates.length).fill(30), {
totalDistanceMeters: totalDistMeters
});
refreshRouteSpeedLimits();
routeInfoEl.style.display = 'block';
routeInfoEl.textContent = `Route: ${totalDistMiles.toFixed(1)} mi | ${Math.round(route.duration / 60)} min`;
return true;
} catch (err) {
alert('Error fetching route: ' + err.message);
return false;
}
}
function startSimulation() {
if (!simulator) return;
clearInterval(routeUpdateInterval);
simulator.currentSpeedMph = 0;
simulator.distanceTraveledMiles = 0;
isPaused = false;
vehicleMarker?.remove();
vehicleMarker = L.circleMarker(simulator.getCurrentPosition(), {
radius: 8,
fillColor: '#3b82f6',
color: '#ffffff',
weight: 2,
opacity: 1,
fillOpacity: 0.95
}).addTo(map);
toggleBtnEl.disabled = false;
toggleBtnEl.textContent = 'Pause';
dwellEl.textContent = '—';
speedLimitEl.textContent = '—';
routeUpdateInterval = setInterval(updateRoute, 100);
}
function togglePause() {
if (!simulator) return;
if (isPaused) {
routeUpdateInterval = setInterval(updateRoute, 100);
toggleBtnEl.textContent = 'Pause';
isPaused = false;
} else {
clearInterval(routeUpdateInterval);
toggleBtnEl.textContent = 'Resume';
isPaused = true;
}
}
function stopSimulation() {
clearInterval(routeUpdateInterval);
routeUpdateInterval = null;
isPaused = false;
toggleBtnEl.textContent = 'Pause';
toggleBtnEl.disabled = true;
}
function resetRoute(resetHint = true) {
stopSimulation();
simulator = null;
routeNodeIds = [];
routeSpeedResolved = [];
planningState = 'start';
clearRouteGraphics();
routeInfoEl.style.display = 'none';
document.getElementById('distance').textContent = '—';
document.getElementById('speed').textContent = '— mph';
document.getElementById('eta').textContent = '—';
document.getElementById('progress').textContent = '0%';
dwellEl.textContent = '—';
speedLimitEl.textContent = '—';
if (resetHint) setHint('Click the map to set a start location.');
}
function updateRoute() {
if (!simulator) return;
simulator.update(0.1);
const status = simulator.getStatus();
if (vehicleMarker) {
vehicleMarker.setLatLng(status.position);
}
document.getElementById('distance').textContent = status.distanceRemaining.toFixed(1) + ' mi';
document.getElementById('speed').textContent = status.currentSpeed.toFixed(1) + ' mph';
document.getElementById('progress').textContent = Math.round(status.progressPct) + '%';
const speedLimit = simulator.speedLimits?.[simulator.currentWaypointIdx] || null;
speedLimitEl.textContent = speedLimit ? Math.round(speedLimit) : '—';
const etaMins = Math.round(status.etaSeconds / 60);
document.getElementById('eta').textContent = etaMins + ' min';
if (status.atStop) {
const remaining = Math.max(0, status.stopDuration - status.stopElapsedTime);
dwellEl.textContent = `${Math.ceil(remaining)}s`;
} else {
dwellEl.textContent = '—';
}
if (status.progressPct >= 100) {
stopSimulation();
setHint('Route complete. Click Reset Route to plan again.');
}
}
</script>
</body>
</html>