-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1201 lines (1048 loc) · 46 KB
/
Copy pathscript.js
File metadata and controls
1201 lines (1048 loc) · 46 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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const map = L.map("map").setView([39.9242, -82.8089], 12);
const overpassUrl = "https://overpass-api.de/api/interpreter";
// Array to store camera locations
let cameras = [];
function fetchSurveillanceData(bounds) {
// Show the loading spinner
document.getElementById("loading").style.display = "block";
// Get the bounds of the current view
const swLat = bounds.getSouthWest().lat;
const swLon = bounds.getSouthWest().lng;
const neLat = bounds.getNorthEast().lat;
const neLon = bounds.getNorthEast().lng;
const query = `
[out:json];
(
node["amenity"="camera"](${swLat},${swLon},${neLat},${neLon});
node["man_made"="surveillance"](${swLat},${swLon},${neLat},${neLon});
);
out body;
`;
fetch(overpassUrl, {
method: "POST",
body: new URLSearchParams({
data: query,
}),
<<<<<<< HEAD
timeout: 10000,
})
.then((response) => {
if (
response.ok &&
response.headers.get("Content-Type").includes("application/json")
) {
return response.json();
} else {
throw new Error("Invalid response format");
=======
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: '© Esri', maxZoom: 19,
}),
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '© CARTO', maxZoom: 19, subdomains: 'abcd',
}),
];
let tileIdx = 0;
const attachErr = (t) => t.on('tileerror', () => {
if (map.hasLayer(t)) { map.removeLayer(t); tileIdx = (tileIdx + 1) % tiles.length; tiles[tileIdx].addTo(map); }
});
attachErr(tiles[0]); attachErr(tiles[1]); attachErr(tiles[2]);
tiles[0].addTo(map);
L.control.layers(Object.fromEntries([
['🗺️ Street', tiles[0]], ['🛰️ Satellite', tiles[1]], ['🌙 Dark', tiles[2]],
]), {}, { position: 'topright', collapsed: true }).addTo(map);
window._map = map;
setupAreaDefine();
loadDefaultCameras();
setupEventListeners();
setupModals();
setupMobilePanel();
setupDirectionsActions();
setTimeout(() => map.invalidateSize(), 120);
}
// ── Region selector ─────────────────────────────────────────────────────────
// Auto-load Ohio cameras on startup
async function loadDefaultCameras() {
const status = document.getElementById('camera-status');
const start = document.getElementById('startAddr');
const end = document.getElementById('endAddr');
const btn = document.getElementById('btn-route');
status.textContent = 'Loading Ohio camera data…';
start.disabled = end.disabled = btn.disabled = true;
try {
const res = await fetch(`${API}/cameras/oh-statewide`);
const cache = await res.json();
if (!res.ok || cache.error) throw new Error(cache.error || 'load failed');
regionCameras = cache.cameras || [];
selectedRegion = 'oh-statewide';
if (!regionCameras.length) { status.textContent = 'No cameras in Ohio cache yet.'; return; }
const age = ((Date.now() - cache.generatedAt) / 3600000).toFixed(1);
status.textContent = regionCameras.length.toLocaleString() + ' Ohio cameras loaded (' + age + 'h old)';
start.disabled = end.disabled = btn.disabled = false;
} catch(e) {
status.textContent = 'Failed to load cameras — refresh to retry.';
}
}
// ── Event listeners ──────────────────────────────────────────────────────────
function setupEventListeners() {
const start = document.getElementById('startAddr');
const end = document.getElementById('endAddr');
const btn = document.getElementById('btn-route');
btn.addEventListener('click', () => {
const s = start.value.trim(), e = end.value.trim();
if (!s || !e) { showError('Enter both a start point and a destination.'); return; }
if (!regionCameras.length) { showError('Camera data not loaded yet.'); return; }
showError('');
routeFromAddresses(s, e);
});
[start, end].forEach(inp => {
inp.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); if (start.value.trim() && end.value.trim()) btn.click(); }
});
});
// Camera avoidance slider — re-score existing routes instantly (no new OSRM calls)
const avoidSlider = document.getElementById('avoid-slider');
const avoidValue = document.getElementById('avoid-value');
if (avoidSlider && avoidValue) {
avoidSlider.addEventListener('input', () => {
const v = avoidSlider.value / 100;
AVOID_CAMERAS = v;
if (v <= 0.2) avoidValue.textContent = 'Fastest';
else if (v <= 0.4) avoidValue.textContent = 'Mostly fast';
else if (v <= 0.6) avoidValue.textContent = 'Balanced';
else if (v <= 0.8) avoidValue.textContent = 'Camera-aware';
else avoidValue.textContent = 'Max camera avoidance';
// Re-score and re-sort existing routes
if (window._scored && window._scored.length > 0) {
const scored = window._scored.map(r => {
const forTurf = r.coords.map(c => [c.lng, c.lat]);
const line = turf.lineString(forTurf);
const routeLen = turf.length(line, { units: 'metres' });
const camScore = routeLen > 0 ? (r.cameraCount / routeLen) * 50000 : 0;
const distScore = r.distance / 1000;
const timeScore = r.duration / 60;
return { ...r, combined: AVOID_CAMERAS * camScore + (1 - AVOID_CAMERAS) * (distScore + timeScore / 10) };
});
scored.sort((a, b) => a.combined - b.combined);
window._scored = scored;
// Remove all old layers (polylines + badge markers)
routeLayers.forEach(l => map.removeLayer(l));
routeLayers = [];
cameraMarkers.forEach(m => m.remove());
cameraMarkers = [];
scored.forEach((r, i) => {
const color = ROUTE_COLORS[i % ROUTE_COLORS.length];
const wt = ROUTE_WEIGHTS[i % ROUTE_WEIGHTS.length];
const coords = r.coords.map(c => [c.lat, c.lng]);
r.line = L.polyline(coords, { color, weight: wt, opacity: 0.85 }).addTo(map);
routeLayers.push(r.line);
r.cameras.forEach(c => {
const m = L.circleMarker([c.lat, c.lon], {
radius: 7, color: '#c0392b', fillColor: '#e74c3c',
fillOpacity: 1, weight: 1.5, opacity: 1,
}).addTo(map);
m.bindTooltip(c.dist + 'm');
cameraMarkers.push(m);
});
const midIdx = Math.floor(coords.length / 2);
const isBest = i === 0;
const camPct = scored[0].cameraCount > 0
? Math.round((1 - r.cameraCount / scored[0].cameraCount) * 100)
: 0;
const badgeText = isBest
? `BEST · ${r.cameraCount} cam${r.cameraCount !== 1 ? 's' : ''}`
: r.cameraCount === 0
? 'CAMERA-FREE'
: `${r.cameraCount} cam${r.cameraCount !== 1 ? 's' : ''} · ${camPct}% more`;
const badge = L.marker(coords[midIdx], {
icon: L.divIcon({
className: 'route-badge', html:
`<div class="route-badge"><span class="route-badge-dot" style="background:${color}"></span>` +
`${badgeText}</div>`,
iconSize: [200, 26], iconAnchor: [100, 13],
}),
}).addTo(map);
routeLayers.push(badge);
});
// Update summary cards to reflect new order
showRouteSummary(scored);
// Re-fetch directions for current best
fetchDirectionsForBest(scored[0]);
>>>>>>> 3d408b9 (Add Mapbox geocoding + 5x camera penalty multiplier)
}
})
.then((data) => {
// Hide the loading spinner after data is fetched
document.getElementById("loading").style.display = "none";
<<<<<<< HEAD
// Process and display camera data...
cameras = [];
data.elements.forEach((element) => {
const lat = element.lat;
const lon = element.lon;
cameras.push({ lat, lon });
L.circleMarker([lat, lon], {
color: "red",
radius: 3,
weight: 1,
opacity: 1,
fillOpacity: 0.4,
=======
// ── Mobile panel ────────────────────────────────────────────────────────────
function setupMobilePanel() {
const panel = document.getElementById('side-panel');
const collapse = document.getElementById('panel-collapse-toggle');
const label = document.getElementById('collapse-label');
if (!collapse || !panel) return;
collapse.addEventListener('click', () => {
panel.classList.toggle('collapsed');
if (label) label.textContent = panel.classList.contains('collapsed') ? 'show' : 'hide';
setTimeout(() => map && map.invalidateSize(), 320);
});
}
// ── Modals ────────────────────────────────────────────────────────────────────
// ── Modal helpers ─────────────────────────────────────────────────────────────
function showModal(id) { const m = document.getElementById(id); if (m) m.removeAttribute('hidden'); }
function hideModal(id) { const m = document.getElementById(id); if (m) m.setAttribute('hidden', ''); }
// ── Help / Legend modals (simple open/close via hidden attribute) ───────────
function setupModals() {
const setup = (btnId, modalId, closeId) => {
const btn = document.getElementById(btnId);
const modal = document.getElementById(modalId);
const close = document.getElementById(closeId);
if (!btn || !modal) return;
btn.addEventListener('click', () => showModal(modalId));
close.addEventListener('click', () => hideModal(modalId));
modal.addEventListener('click', e => { if (e.target === modal) hideModal(modalId); });
};
setup('btn-help', 'modal-help', 'close-help');
setup('btn-legend', 'modal-legend', 'close-legend');
}
// ── Directions actions ──────────────────────────────────────────────────────
function setupDirectionsActions() {
const copyBtn = document.getElementById('btn-copy-dirs');
const printBtn = document.getElementById('btn-print-dir');
if (copyBtn) copyBtn.addEventListener('click', copyDirections);
if (printBtn) printBtn.addEventListener('click', printDirections);
}
// ── Geocoding ───────────────────────────────────────────────────────────────
let _lastGeo = 0;
// Geocode via Mapbox (server-side proxy keeps the API key hidden)
async function geocode(addr) {
const wait = 1000 - (Date.now() - _lastGeo);
if (wait > 0) await new Promise(r => setTimeout(r, wait));
_lastGeo = Date.now();
const res = await fetch(API + '/geocode?address=' + encodeURIComponent(addr));
if (!res.ok) throw new Error('Geocoding service error.');
const data = await res.json();
if (data.error || !data.lat) throw new Error(data.error || `Address not found: "${addr}"`);
return { lat: data.lat, lon: data.lon };
}
// ── Routing ─────────────────────────────────────────────────────────────────
async function routeFromAddresses(startAddr, endAddr) {
setLoading(true, 'Finding routes…');
try {
// Call sequentially — Nominatim rate-limits to 1 req/sec and checks via _lastGeo
const start = await geocode(startAddr);
const end = await geocode(endAddr);
setLoading(true, 'Routing…');
if (isRouting) return;
isRouting = true;
clearRouteState();
const waypoints = `${start.lon},${start.lat};${end.lon},${end.lat}`;
const routeUrl =
MAPBOX_KEY
? `https://api.mapbox.com/directions/v5/mapbox/driving/${waypoints}?access_token=${MAPBOX_KEY}&overview=full&geometries=polyline&steps=false&alternatives=3`
: `/api/routeproxy/driving/${waypoints}?overview=full&geometries=polyline&steps=false&alternatives=3`;
let data;
try {
const res = await fetch(routeUrl);
data = await res.json();
} catch(err) {
setLoading(false); isRouting = false;
showError('Routing server unreachable. Check your Mapbox API key in script.js.');
return;
}
const routes = data.routes;
if (!routes?.length) {
setLoading(false); isRouting = false;
showError('No routes found between these addresses.');
return;
}
const rawRoutes = data.routes.map(r => ({
distance: r.distance,
duration: r.duration,
coords: polyline.decode(r.geometry, 5).map(([lat, lng]) => L.latLng(lat, lng)),
}));
onRoutesReady(rawRoutes);
} catch(err) {
setLoading(false); isRouting = false;
showError(err.message || 'Routing failed.');
}
}
// ── Routes ready ─────────────────────────────────────────────────────────────
function onRoutesReady(rawRoutes) {
try {
const scored = rawRoutes.map((r, i) => scoreRouteDirect(r, i));
// Sort by combined score (camera exposure + speed trade-off)
scored.sort((a, b) => a.combined - b.combined);
window._scored = scored;
for (let i = 0; i < scored.length; i++) {
const r = scored[i];
const color = ROUTE_COLORS[i % ROUTE_COLORS.length];
const wt = ROUTE_WEIGHTS[i % ROUTE_WEIGHTS.length];
const coords = r.coords.map(c => [c.lat, c.lng]);
r.line = L.polyline(coords, { color, weight: wt, opacity: 0.85 }).addTo(map);
routeLayers.push(r.line);
// Camera markers — shown on every route, always visible
r.cameras.forEach(c => {
const m = L.circleMarker([c.lat, c.lon], {
radius: 7, color: '#c0392b', fillColor: '#e74c3c',
fillOpacity: 1, weight: 1.5, opacity: 1,
>>>>>>> 3d408b9 (Add Mapbox geocoding + 5x camera penalty multiplier)
}).addTo(map);
});
// Check for cameras along the route
checkForCamerasOnRoute();
})
.catch((error) => {
// Hide loading spinner and log error
document.getElementById("loading").style.display = "none";
console.error("Error fetching OSM data:", error);
});
}
function checkForCamerasOnRoute() {
const waypoints = control.getWaypoints();
console.log("Waypoints:", waypoints);
<<<<<<< HEAD
if (waypoints.length < 2) {
console.error("Waypoints not set properly.");
=======
// Bounding box of route + 1km pad (~0.009 deg lat)
const PAD = 0.009;
const lats = route.coords.map(c => c.lat);
const lons = route.coords.map(c => c.lng);
const minLat = Math.min(...lats) - PAD, maxLat = Math.max(...lats) + PAD;
const minLon = Math.min(...lons) - PAD, maxLon = Math.max(...lons) + PAD;
// Route length in metres (for distance-normalised score)
const routeLen = turf.length(line, { units: 'metres' });
const near = [];
for (const cam of regionCameras) {
// Fast bounding-box cull
if (cam.lat < minLat || cam.lat > maxLat || cam.lon < minLon || cam.lon > maxLon) continue;
// Perpendicular distance from camera to route
const isPTZ = cam.tags['camera:type'] === 'panning';
const maxDist = isPTZ ? CAM_DIST_PTZ : CAM_DIST;
const d = turf.pointToLineDistance(
turf.point([cam.lon, cam.lat]), line, { units: 'metres' }
);
if (d <= maxDist) {
const pt = turf.nearestPointOnLine(line, turf.point([cam.lon, cam.lat]), { units: 'metres' });
near.push({ ...cam, dist: Math.round(d), routePos: pt.properties.location || 0 });
}
}
// Combined score: weighted mix of camera exposure + distance + time
// Higher = worse. AVOID_CAMERAS=1 means camera count dominates.
const camScore = routeLen > 0 ? (near.length / routeLen) * 50000 : 0;
const distScore = route.distance / 1000;
const timeScore = route.duration / 60;
const combined = AVOID_CAMERAS * camScore + (1 - AVOID_CAMERAS) * (distScore + timeScore / 10);
return {
coords: route.coords,
distance: route.distance,
duration: route.duration,
cameraCount: near.length,
cameras: near,
camScore,
combined,
line: null,
};
}
// ── Directions ─────────────────────────────────────────────────────────────
let _dirSteps = [];
let _routeCameras = [];
async function fetchDirectionsForBest(bestRoute) {
const dirsPanel = document.getElementById('directions-panel');
const dirsBody = document.getElementById('directions-body');
if (!dirsPanel || !dirsBody) return;
dirsPanel.removeAttribute('hidden');
dirsBody.innerHTML = '<div class="dirs-empty">Loading directions…</div>';
try {
const coords = bestRoute.coords;
if (!coords || coords.length < 2) throw new Error('No coordinates');
_routeCameras = bestRoute.cameras || [];
const totalDist = bestRoute.distance || 1;
const start = coords[0];
const end = coords[coords.length - 1];
const wp = `${start.lng},${start.lat};${end.lng},${end.lat}`;
const dirUrl =
MAPBOX_KEY
? `https://api.mapbox.com/directions/v5/mapbox/driving/${wp}?access_token=${MAPBOX_KEY}&overview=false&steps=true`
: `/api/routeproxy/driving/${wp}?overview=false&steps=true`;
let dirData;
try { dirData = await (await fetch(dirUrl)).json(); }
catch { throw new Error('Could not reach routing server.'); }
if (!dirData.routes?.[0]?.legs?.[0]?.steps) {
throw new Error('No directions returned.');
}
const steps = dirData.routes[0].legs[0].steps;
_dirSteps = steps.map(s => ({
maneuver: s.maneuver?.type || 'continue',
text: s.name || '(unnamed road)',
distance: formatDistance(s.distance),
distRaw: s.distance || 0,
modifier: s.maneuver?.modifier || '',
}));
renderDirections(_dirSteps, _routeCameras, totalDist);
} catch(err) {
dirsBody.innerHTML =
'<div class="dirs-empty dirs-error">Directions unavailable: ' + err.message + '</div>';
}
}
function renderDirections(steps, cameras, totalDist) {
const body = document.getElementById('directions-body');
if (!body) return;
// Compute cumulative distance boundaries for each step
const stepBoundaries = [];
let cum = 0;
steps.forEach(s => {
stepBoundaries.push({ start: cum, end: cum + (s.distRaw || 0) });
cum += s.distRaw || 0;
});
// Assign each camera to the step it falls within, using its true position along route
const camStepIdx = cameras.map(c => {
const camCum = c.routePos || 0;
const idx = stepBoundaries.findIndex(b => camCum <= b.end);
return Math.max(0, idx === -1 ? stepBoundaries.length - 1 : idx);
});
let html = '<div class="dirs-list">';
html +=
'<div class="dir-step dir-step--start">' +
'<div class="dir-text"><strong>Depart</strong> — Start here</div>' +
'</div>';
steps.forEach((s, stepIdx) => {
const suffix = s.modifier ? ' ' + capitalize(s.modifier) : '';
html +=
'<div class="dir-step">' +
'<div class="dir-content">' +
'<div class="dir-text">' + capitalize(s.maneuver) + suffix + ' — ' + s.text + '</div>' +
'<div class="dir-distance">' + s.distance + '</div>' +
'</div>' +
'</div>';
// Cameras that appear during this step
const relevant = cameras.filter((c, ci) => camStepIdx[ci] === stepIdx);
if (relevant.length > 0) {
html += '<div class="dir-step dir-step--cam">' +
'<div class="dir-text dir-cam-label">' + relevant.length + ' camera' + (relevant.length !== 1 ? 's' : '') + ' on this segment</div>' +
relevant.map(c => {
const loc = c.tags?.name || 'near ' + (s.text || 'this road');
return '<div class="dir-text dir-cam-item">● ' + loc + ' (' + c.dist + 'm from road)</div>';
}).join('') +
'</div>';
}
});
html +=
'<div class="dir-step dir-step--end">' +
'<div class="dir-text"><strong>Arrive</strong> — Destination reached</div>' +
'</div>';
html += '</div>';
body.innerHTML = html;
}
function formatDistance(m) {
if (m < 1000) return Math.round(m) + ' m';
return (m / 1000).toFixed(1) + ' km';
}
function capitalize(s) {
if (!s) return '';
return s.charAt(0).toUpperCase() + s.slice(1).replace(/_/g, ' ');
}
function getDirectionsText(steps, cameras, totalDist) {
const lines = ['SCARP — Turn-by-turn directions', ''];
const stepBoundaries = [];
let cum = 0;
steps.forEach(s => {
stepBoundaries.push({ start: cum, end: cum + (s.distRaw || 0) });
cum += s.distRaw || 0;
});
const camStepIdx = cameras.map(c => {
const camCum = c.routePos || 0;
const idx = stepBoundaries.findIndex(b => camCum <= b.end);
return Math.max(0, idx === -1 ? stepBoundaries.length - 1 : idx);
});
steps.forEach((s, i) => {
const suffix = s.modifier ? ' ' + capitalize(s.modifier) : '';
lines.push(
(i + 1) + '. ' + capitalize(s.maneuver) + suffix + ' — ' + s.text + ' (' + s.distance + ')'
);
const relevant = cameras.filter((c, ci) => camStepIdx[ci] === i);
if (relevant.length > 0) {
lines.push(' Cameras: ' + relevant.map(c => (c.tags?.name || 'near ' + _dirSteps[i]?.text || 'this segment') + ' (' + c.dist + 'm)').join('; '));
}
});
lines.push('');
lines.push('Generated by SCARP — Avoid Surveillance Cameras');
return lines.join('\n');
}
function flashBtn(btn, msg) {
if (!btn) return;
const orig = btn.innerHTML;
btn.innerHTML = msg;
setTimeout(() => { btn.innerHTML = orig; }, 1800);
}
function copyDirections() {
if (!_dirSteps.length) return;
const text = getDirectionsText(_dirSteps, _routeCameras, window._scored?.[0]?.distance || 1);
const btn = document.getElementById('btn-copy-dirs');
// Reliable cross-browser copy: create a temporary editable element
// (works in Brave, Firefox, Safari where clipboard API may be restricted)
const target = Object.assign(document.createElement('div'), {
textContent: text,
style: 'position:fixed;width:200px;height:50px;top:0;left:0;opacity:0;overflow:hidden;' +
'white-space:pre-wrap;word-wrap:break-word;font-size:13px;line-height:1.5;padding:12px;'
});
document.body.appendChild(target);
const range = document.createRange();
range.selectNodeContents(target);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
let ok = false;
try { ok = document.execCommand('copy'); } catch { ok = false; }
sel.removeAllRanges();
target.remove();
flashBtn(btn, ok ? 'Copied!' : 'Select all text');
// If execCommand failed, select the directions text so user can Ctrl+A / right-click copy
if (!ok) {
const body = document.getElementById('directions-body');
if (body) {
const allText = Array.from(body.querySelectorAll('.dir-text')).map(el => el.innerText).join('\n');
const ta = Object.assign(document.createElement('textarea'), {
value: text, style: 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0'
});
document.body.appendChild(ta);
ta.select();
try { document.execCommand('copy'); } catch {}
ta.remove();
}
}
}
function printDirections() {
if (!_dirSteps.length) return;
// Rebuild step+camera HTML (same logic as renderDirections)
const stepBoundaries = [];
let cum = 0;
_dirSteps.forEach(s => {
stepBoundaries.push({ start: cum, end: cum + (s.distRaw || 0) });
cum += s.distRaw || 0;
});
const camStepIdx = _routeCameras.map(c => {
const camCum = c.routePos || 0;
const idx = stepBoundaries.findIndex(b => camCum <= b.end);
return Math.max(0, idx === -1 ? stepBoundaries.length - 1 : idx);
});
const rows = [];
rows.push('<p><strong>Depart — Start here</strong></p>');
_dirSteps.forEach((s, i) => {
const suffix = s.modifier ? ' ' + capitalize(s.modifier) : '';
rows.push('<div class="step"><strong>' + (i + 1) + '. ' + capitalize(s.maneuver) + suffix +
'</strong> — ' + s.text + ' <span class="dist">(' + s.distance + ')</span></div>');
const relevant = _routeCameras.filter((c, ci) => camStepIdx[ci] === i);
relevant.forEach(c => {
const loc = c.tags?.name || (_dirSteps[i]?.text || 'this segment');
rows.push('<div class="cam">● Camera near ' + loc + ' (' + c.dist + 'm from road)</div>');
});
});
rows.push('<p><strong>Arrive — Destination reached</strong></p>');
const win = window.open('', '_blank', 'width=600,height=800');
if (!win) return;
win.document.write(
'<!doctype html><html><head><title>SCARP Directions</title>' +
'<style>body{font-family:Georgia,serif;padding:24px;line-height:1.7;max-width:540px;margin:0 auto;}' +
'h2{font-size:18px;border-bottom:2px solid #000;padding-bottom:8px;}' +
'h4{font-size:11px;color:#888;text-transform:uppercase;margin:4px 0 0;}' +
'.step{margin-bottom:8px;padding:5px 0 5px 8px;border-left:3px solid #333;}' +
'.dist{color:#555;font-size:12px;}' +
'.cam{color:#c0392b;font-size:12px;padding:2px 0 2px 20px;}' +
'hr{margin:16px 0;}</style></head><body>' +
'<h2>SCARP — Turn-by-turn directions</h2>' +
'<h4>Generated by SCARP — Avoid Surveillance Cameras</h4><hr/>' +
rows.join('') +
'<hr/><p style="font-size:12px;color:#888;">Generated by SCARP — Avoid Surveillance Cameras</p>' +
'</body></html>'
);
win.document.close();
win.focus();
win.print();
win.close();
}
// ── UI helpers ───────────────────────────────────────────────────────────────
function setLoading(on, msg) {
const el = document.getElementById('loading');
if (on) el.removeAttribute('hidden'); else el.setAttribute('hidden', '');
document.getElementById('loading-msg').textContent = msg || 'Working…';
}
function showError(msg) {
document.getElementById('panel-error').textContent = msg;
}
function clearRouteState() {
routeLayers.forEach(l => l.remove()); routeLayers = [];
cameraMarkers.forEach(m => m.remove()); cameraMarkers = [];
_dirSteps = [];
document.getElementById('route-summary').classList.remove('visible');
const dp = document.getElementById('directions-panel');
if (dp) dp.setAttribute('hidden', '');
}
// ── Route summary ─────────────────────────────────────────────────────────────
function showRouteSummary(scored) {
const summary = document.getElementById('route-summary');
summary.classList.add('visible');
const best = scored[0];
const camClean = best.cameraCount === 0;
const camClass = camClean ? 'clean' : '';
const camText = camClean
? 'Zero cameras on this route'
: best.cameraCount + ' camera' + (best.cameraCount !== 1 ? 's' : '') + ' on this route';
const heroHTML =
'<div class="summary-hero">' +
'<div class="summary-hero-label">Best route found</div>' +
'<div class="summary-hero-stats">' +
'<div class="summary-hero-stat"><strong>' + (best.distance / 1000).toFixed(1) + '</strong> km</div>' +
'<div class="summary-hero-stat"><strong>' + fmtDuration(best.duration) + '</strong></div>' +
'<div class="summary-hero-cams ' + camClass + '">' + camText + '</div>' +
'</div>' +
'</div>';
const cardsHTML = scored.map((r, i) => {
const color = ROUTE_COLORS[i % ROUTE_COLORS.length];
const isBest = i === 0;
const pillCls = r.cameraCount === 0 ? 'cam-pill--clear' : r.cameraCount < 20 ? 'cam-pill--low' : 'cam-pill--high';
const pillTxt = r.cameraCount === 0 ? '0 cams' : r.cameraCount + ' cam' + (r.cameraCount !== 1 ? 's' : '');
const hasCams = r.cameras && r.cameras.length > 0;
let camHTML = '';
if (hasCams) {
const shown = r.cameras.slice(0, 15);
camHTML = '<div class="cam-detail" id="cam-detail-' + i + '">' +
'<div class="cam-detail-header">' + r.cameras.length + ' camera' + (r.cameras.length !== 1 ? 's' : '') + ' within '+ CAM_DIST +'m of this route</div>' +
shown.map(c =>
'<div class="cam-detail-item">' +
'<span class="cam-detail-dot"></span>' +
'<div class="cam-detail-info">' +
'<div class="cam-detail-dist">~' + c.dist + 'm from route</div>' +
'<div class="cam-detail-coords">' + c.lat.toFixed(5) + ', ' + c.lon.toFixed(5) + '</div>' +
'</div>' +
'</div>'
).join('');
if (r.cameras.length > 15) camHTML += '<div class="cam-detail-more">+' + (r.cameras.length - 15) + ' more</div>';
camHTML += '</div>';
} else {
camHTML = '<div class="cam-detail open" id="cam-detail-' + i + '">' +
'<div class="cam-detail-item"><div class="cam-detail-info">No cameras within '+ CAM_DIST +'m of this route</div></div>' +
'</div>';
}
const expandBtn = hasCams
? '<button class="cam-toggle-btn" id="toggle-btn-' + i + '" onclick="toggleCamDetail(' + i + ')">' +
'<span id="arrow-' + i + '">▼</span> Show cameras</button>'
: '';
return '<div class="route-card' + (isBest ? ' route-card--best' : '') + '" data-i="' + i + '">' +
'<div class="route-swatch" style="background:' + color + '"></div>' +
'<div class="route-body">' +
'<div class="route-card-header">' +
'<div class="route-rank">' +
'<span class="route-rank-badge ' + (isBest ? 'route-rank-badge--best' : 'route-rank-badge--alt') + '">' +
(isBest ? '★' : (i + 1)) + '</span>' +
'<span class="route-rank-label">' + (isBest ? 'Best' : 'Alt ' + (i + 1)) + '</span>' +
'</div>' +
'<div class="route-card-meta">' +
'<span><strong>' + (r.distance / 1000).toFixed(1) + '</strong> km</span>' +
'<span><strong>' + fmtDuration(r.duration) + '</strong></span>' +
'</div>' +
'</div>' +
'<div class="route-card-footer">' +
'<span class="cam-pill ' + pillCls + '">' + pillTxt + '</span>' +
expandBtn +
'</div>' +
camHTML +
'</div>' +
'</div>';
}).join('');
summary.innerHTML = heroHTML + cardsHTML;
}
function fmtDuration(s) {
if (!s || s < 0) return '—';
if (s < 60) return Math.round(s) + 's';
if (s < 3600) return Math.round(s / 60) + ' min';
const h = Math.floor(s / 3600);
const m = Math.round((s % 3600) / 60);
return m > 0 ? h + 'h ' + m + 'm' : h + 'h';
}
// ── Camera toggle (expand/collapse only — no route color changes) ───────────
window.toggleCamDetail = function(i) {
const detail = document.getElementById('cam-detail-' + i);
const arrow = document.getElementById('arrow-' + i);
const toggleBtn = document.getElementById('toggle-btn-' + i);
if (!detail) return;
const isOpen = detail.classList.contains('open');
document.querySelectorAll('.cam-detail.open').forEach(el => el.classList.remove('open'));
document.querySelectorAll('.cam-toggle-btn span.open').forEach(el => el.classList.remove('open'));
document.querySelectorAll('.cam-toggle-btn.open').forEach(el => { el.classList.remove('open'); el.textContent = ''; });
if (!isOpen) {
detail.classList.add('open');
if (arrow) { arrow.classList.add('open'); }
if (toggleBtn) {
toggleBtn.textContent = 'Hide cameras';
toggleBtn.classList.add('open');
}
} else {
if (toggleBtn) toggleBtn.textContent = 'Show cameras';
cameraMarkers.forEach(m => m.remove()); cameraMarkers = [];
}
};
// ════════════════════════════════════════════════════════════════════════════
// User-defined area: draw rect on map → name → fetch cameras from Overpass
// ════════════════════════════════════════════════════════════════════════════
let drawnItem = null; // { name, bbox, drawLayer, layer }
let drawControl = null;
function setupAreaDefine() {
document.getElementById('btn-define-area').addEventListener('click', openAreaModal);
document.getElementById('area-modal-close').addEventListener('click', closeAreaModal);
document.getElementById('btn-cancel-area').addEventListener('click', closeAreaModal);
document.getElementById('btn-start-draw').addEventListener('click', startAreaDraw);
document.getElementById('area-name').addEventListener('input', validateAreaName);
}
function isUserRegion(id) {
return id && id.startsWith(USER_REGION_PREFIX);
}
function openAreaModal() {
drawnItem = null;
document.getElementById('area-name').value = '';
document.getElementById('area-hint').style.display = 'none';
document.getElementById('area-draw-status').style.display = 'none';
document.getElementById('btn-start-draw').textContent = 'Draw on map';
document.getElementById('btn-start-draw').disabled = false;
document.getElementById('btn-start-draw').onclick = startAreaDraw;
document.getElementById('btn-define-area').textContent = 'Cancel';
document.getElementById('btn-define-area').classList.add('drawing');
showModal('area-modal');
}
function closeAreaModal() {
cancelDraw();
document.getElementById('btn-define-area').textContent = 'Define custom area';
document.getElementById('btn-define-area').classList.remove('drawing');
hideModal('area-modal');
}
function validateAreaName() {
const val = document.getElementById('area-name').value.trim();
const hint = document.getElementById('area-hint');
if (!val) { hint.textContent = ''; hint.style.display = 'none'; return false; }
if (val.length < 3) {
hint.textContent = 'Name must be at least 3 characters.'; hint.style.display = 'block';
return false;
}
hint.textContent = ''; hint.style.display = 'none';
return true;
}
function startAreaDraw() {
if (!validateAreaName()) return;
hideModal('area-modal');
document.getElementById('btn-start-draw').disabled = true;
document.getElementById('btn-start-draw').textContent = 'Draw on map…';
document.getElementById('btn-define-area').textContent = 'Drawing…';
document.getElementById('btn-define-area').classList.add('drawing');
cancelDraw();
const drawLayer = new L.FeatureGroup();
map.addLayer(drawLayer);
const dc = new L.Draw.Rectangle(map, {
shapeOptions: { color: '#2ecc71', weight: 2, fillColor: '#2ecc71', fillOpacity: 0.12 },
});
dc.enable();
map.once('draw:created', function(e) {
const layer = e.layer;
drawLayer.addLayer(layer);
const bounds = layer.getBounds();
const S = bounds.getSouth(), W = bounds.getWest();
const N = bounds.getNorth(), E = bounds.getEast();
let bbox = [S, W, N, E];
let capped = false;
const latSpan = N - S, lonSpan = E - W;
if (latSpan > MAX_BBOX || lonSpan > MAX_BBOX) {
const cLat = (N + S) / 2, cLon = (E + W) / 2, hs = MAX_BBOX / 2;
bbox = [cLat - hs, cLon - hs, cLat + hs, cLon + hs];
capped = true;
layer.setBounds(L.latLngBounds(L.latLng(bbox[0], bbox[1]), L.latLng(bbox[2], bbox[3])));
}
const name = document.getElementById('area-name').value.trim();
drawnItem = { name, bbox, drawLayer, layer };
const previewEl = document.getElementById('area-bbox-preview');
let txt = bbox[2].toFixed(2) + '°N – ' + bbox[0].toFixed(2) + '°N, ' +
Math.abs(bbox[1]).toFixed(2) + '°W – ' + Math.abs(bbox[3]).toFixed(2) + '°W';
if (capped) txt += ' (capped to 6°×6°)';
previewEl.textContent = txt;
document.getElementById('area-draw-status').style.display = 'block';
document.getElementById('btn-start-draw').textContent = 'Fetch cameras';
document.getElementById('btn-start-draw').disabled = false;
document.getElementById('btn-start-draw').onclick = confirmAreaFetch;
document.getElementById('area-modal').hidden = false;
showModal('area-modal');
});
}
function cancelDraw() {
if (drawnItem) { map.removeLayer(drawnItem.drawLayer); drawnItem = null; }
document.getElementById('area-draw-status').style.display = 'none';
document.getElementById('btn-start-draw').textContent = 'Draw on map';
document.getElementById('btn-start-draw').disabled = false;
document.getElementById('btn-start-draw').onclick = startAreaDraw;
}
function confirmAreaFetch() {
if (!drawnItem) return;
const { name, bbox } = drawnItem;
if (!name.trim()) {
document.getElementById('camera-status').textContent = 'Please enter a name for your area.';
>>>>>>> 3d408b9 (Add Mapbox geocoding + 5x camera penalty multiplier)
return;
}
// Find the route polyline on the map
let routePolylines = []; // To hold multiple polylines
map.eachLayer((layer) => {
if (layer instanceof L.Polyline) {
routePolylines.push(layer); // Collect all route polylines
}
});
if (routePolylines.length === 0) {
console.error("Route polylines not found on the map.");
return;
}
// Convert route polylines into Turf.js lineStrings
const routeLines = routePolylines.map((polyline) => {
const routeCoords = polyline
.getLatLngs()
.map((latLng) => [latLng.lng, latLng.lat]);
return turf.lineString(routeCoords);
});
// Clear the list of cameras in the UI
const cameraListDiv = document.getElementById("cameraList");
cameraListDiv.innerHTML = "<h3>Intersecting Cameras:</h3>"; // Reset the list
// Collect cameras that interact with any of the routes
let camerasToAvoid = [];
cameras.forEach((camera) => {
const cameraPoint = turf.point([camera.lon, camera.lat]);
const buffer = turf.buffer(cameraPoint, 50, { units: "meters" }); // 50m buffer to avoid camera
// Check if the route intersects with the camera's buffer for any of the route lines
routeLines.forEach((routeLine) => {
if (turf.booleanIntersects(routeLine, buffer)) {
camerasToAvoid.push(camera); // Collect cameras to avoid
console.log(
`Camera at (${camera.lat}, ${camera.lon}) interacts with the route!`,
);
// Make the camera more visible on the map by changing its style
L.circleMarker([camera.lat, camera.lon], {
color: "red",
radius: 7, // Increase size of marker
weight: 3,
opacity: 1,
fillOpacity: 0.4, // Increase fill opacity
})
.addTo(map)
.bindPopup(`Camera at (${camera.lat}, ${camera.lon})`);
// Add the camera to the list in the bottom right corner
const cameraItem = document.createElement("div");
cameraItem.classList.add("camera-item");
cameraItem.innerHTML = `Camera at (${camera.lat.toFixed(4)}, ${camera.lon.toFixed(4)})`;
cameraListDiv.appendChild(cameraItem);
}
});
});
// If cameras to avoid are found, recalculate the route
if (camerasToAvoid.length > 0) {
avoidCamerasAndRecalculateRoute(camerasToAvoid);
}
}
async function geocodeAddress(street, city, state, zip) {
const params = new URLSearchParams({
street: street,
city: city,
state: state,
postalcode: zip,
country: "USA",
format: "json",
limit: 1
});
const url = `https://nominatim.openstreetmap.org/search?${params.toString()}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error("Geocoding request failed");
}
const data = await response.json();
console.log("Geocode response:", data);
if (!data || data.length === 0) {
throw new Error("Address not found");
}
return {
lat: parseFloat(data[0].lat),
lon: parseFloat(data[0].lon)
};