forked from gordon-williams/arc-timeline-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap-tools.js
More file actions
1692 lines (1467 loc) · 58.8 KB
/
Copy pathmap-tools.js
File metadata and controls
1692 lines (1467 loc) · 58.8 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
/**
* Map Tools - Measurement and Route Search
* Part of Arc Timeline Diary Reader
*
* Contains:
* - MeasurementTool class - measuring distances on the map
* - Route Search functions - From/To location search with OSRM routing
* - Utility functions for distance calculation
*/
// ========== Utility Functions ==========
// Haversine formula for distance between two points (returns km)
function calculateDistanceKm(lat1, lng1, lat2, lng2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLng = (lng2 - lng1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLng/2) * Math.sin(dLng/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
function formatSearchDistance(km) {
if (km < 1) {
return `${(km).toFixed(2)} km`;
} else if (km < 10) {
return `${km.toFixed(1)} km`;
} else {
return `${Math.round(km)} km`;
}
}
/**
* Fetch elevation data for route coordinates using Open-Elevation API
* Samples coordinates for longer routes, batches requests for very long routes
* @param {Array} coords - Array of [lat, lng] coordinates
* @returns {Promise<Array>} - Array of {lat, lng, elevation} objects, or null if failed
*/
async function fetchRouteElevation(coords) {
if (!coords || coords.length === 0) return null;
// Target ~500 points for good detail, max 200 per API request batch
const maxPoints = 500;
const batchSize = 200;
let sampledCoords;
if (coords.length <= maxPoints) {
sampledCoords = coords;
} else {
// Sample evenly, always include first and last points
const step = (coords.length - 1) / (maxPoints - 1);
sampledCoords = [];
for (let i = 0; i < maxPoints; i++) {
const idx = Math.round(i * step);
sampledCoords.push(coords[idx]);
}
}
try {
// Use Open-Elevation API (free, no key required)
// Batch requests if needed
const allResults = [];
for (let i = 0; i < sampledCoords.length; i += batchSize) {
const batch = sampledCoords.slice(i, i + batchSize);
const locations = batch.map(c => ({ latitude: c[0], longitude: c[1] }));
const response = await fetch('https://api.open-elevation.com/api/v1/lookup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ locations })
});
if (!response.ok) throw new Error('Elevation API request failed');
const data = await response.json();
if (data.results && data.results.length > 0) {
allResults.push(...data.results);
}
// Small delay between batches to be nice to the API
if (i + batchSize < sampledCoords.length) {
await new Promise(r => setTimeout(r, 100));
}
}
if (allResults.length > 0) {
return allResults.map(r => ({
lat: r.latitude,
lng: r.longitude,
elevation: r.elevation
}));
}
} catch (err) {
console.warn('Elevation fetch failed:', err.message);
}
return null;
}
/**
* Calculate elevation statistics from elevation data
* @param {Array} elevationData - Array of {elevation} objects
* @returns {Object} - {gain, loss, min, max}
*/
function calculateElevationStats(elevationData) {
if (!elevationData || elevationData.length < 2) return null;
let gain = 0, loss = 0;
let min = elevationData[0].elevation;
let max = elevationData[0].elevation;
for (let i = 1; i < elevationData.length; i++) {
const prev = elevationData[i - 1].elevation;
const curr = elevationData[i].elevation;
const diff = curr - prev;
if (diff > 0) gain += diff;
else loss += Math.abs(diff);
if (curr < min) min = curr;
if (curr > max) max = curr;
}
return { gain: Math.round(gain), loss: Math.round(loss), min: Math.round(min), max: Math.round(max) };
}
// ========== Measurement Tool ==========
class MeasurementTool {
#map = null;
#active = false;
#points = [];
#markers = [];
#lines = [];
#popup = null;
#rubberBand = null;
#mouseMoveHandler = null;
constructor(map) {
this.#map = map;
// Bind handlers
this.#mouseMoveHandler = (e) => this.#onMouseMove(e);
}
get isActive() {
return this.#active;
}
toggle() {
if (this.#active) {
// Currently measuring - stop measuring but keep measurement visible
this.#deactivate();
} else if (this.#points.length > 0) {
// Has existing measurement - clear it
this.clear();
// Ensure button is inactive
const btn = document.getElementById('measureBtn');
if (btn) btn.classList.remove('active');
} else {
// No measurement - start measuring
this.#activate();
}
}
#activate() {
this.#active = true;
this.clear();
// Update button state - get fresh reference
const btn = document.getElementById('measureBtn');
if (btn) {
btn.classList.add('active');
}
// Change cursor
const mapContainer = this.#map.getContainer();
mapContainer.style.cursor = 'crosshair';
// Enable rubber band preview
this.#map.on('mousemove', this.#mouseMoveHandler);
}
#deactivate() {
this.#active = false;
// Only remove active class if no measurements exist
// Button stays active-looking while measurement is displayed
if (this.#points.length === 0) {
const btn = document.getElementById('measureBtn');
if (btn) {
btn.classList.remove('active');
}
}
// Restore cursor
const mapContainer = this.#map.getContainer();
mapContainer.style.cursor = '';
// Disable rubber band
this.#map.off('mousemove', this.#mouseMoveHandler);
this.#removeRubberBand();
}
#onMouseMove(e) {
if (!this.#active || this.#points.length === 0) return;
const lastPoint = this.#points[this.#points.length - 1];
if (!this.#rubberBand) {
this.#rubberBand = L.polyline([lastPoint, e.latlng], {
color: '#ff5722',
weight: 2,
dashArray: '5, 10',
opacity: 0.6,
interactive: false
}).addTo(this.#map);
} else {
this.#rubberBand.setLatLngs([lastPoint, e.latlng]);
}
}
#removeRubberBand() {
if (this.#rubberBand) {
this.#map.removeLayer(this.#rubberBand);
this.#rubberBand = null;
}
}
handleClick(e) {
if (!this.#active) return;
const latlng = e.latlng;
const self = this;
const mapContainer = this.#map.getContainer();
this.#points.push(latlng);
// Remove rubber band - it will recreate from new point on next mousemove
this.#removeRubberBand();
// Determine marker color: green for start, orange for intermediate
const isFirst = this.#points.length === 1;
const markerColor = isFirst ? '#4caf50' : '#ff5722';
// Add marker
const marker = L.circleMarker(latlng, {
radius: 6,
fillColor: markerColor,
color: '#fff',
weight: 2,
fillOpacity: 1,
interactive: true
}).addTo(this.#map);
this.#markers.push(marker);
// Draw line to previous point
if (this.#points.length > 1) {
const prevPoint = this.#points[this.#points.length - 2];
const line = L.polyline([prevPoint, latlng], {
color: '#ff5722',
weight: 4,
dashArray: '10, 10',
interactive: true
}).addTo(this.#map);
// Make line clickable to zoom and show popup
line.on('click', (e) => {
L.DomEvent.stopPropagation(e);
if (!this.#active && this.#points.length > 1) {
this.#showDistance();
this.zoomToFit();
}
});
// Hover effect (use closure - 'self' for class, 'this' for Leaflet)
line.on('mouseover', function() {
if (!self.isActive) {
this.setStyle({ weight: 6 });
}
});
line.on('mouseout', function() {
this.setStyle({ weight: 4 });
});
this.#lines.push(line);
this.#showDistance();
}
// Make markers clickable - option/alt-click to undo
marker.on('click', (e) => {
L.DomEvent.stopPropagation(e);
// Option/Alt-click to undo last point (while measuring)
if (e.originalEvent.altKey && this.#active) {
this.undoLastPoint();
return;
}
// Normal click when finished - zoom to fit and show popup
if (!this.#active && this.#points.length > 1) {
this.#showDistance();
this.zoomToFit();
}
});
// Hover effect for markers
marker.on('mouseover', function() {
if (!self.isActive) {
this.setRadius(8);
} else {
mapContainer.style.cursor = 'pointer';
}
});
marker.on('mouseout', function() {
this.setRadius(6);
if (self.isActive) {
mapContainer.style.cursor = 'crosshair';
}
});
}
undoLastPoint() {
if (this.#points.length === 0) return;
// Remove last point
this.#points.pop();
// Remove last marker
if (this.#markers.length > 0) {
const lastMarker = this.#markers.pop();
this.#map.removeLayer(lastMarker);
}
// Remove last line
if (this.#lines.length > 0) {
const lastLine = this.#lines.pop();
this.#map.removeLayer(lastLine);
}
// Update distance display
if (this.#points.length > 1) {
this.#showDistance();
} else {
// Close popup if less than 2 points
if (this.#popup) {
this.#map.closePopup(this.#popup);
this.#popup = null;
}
}
}
handleDoubleClick(e) {
if (!this.#active) return;
this.finish();
}
finish() {
if (this.#points.length > 1) {
this.#showDistance();
this.zoomToFit();
}
this.#deactivate();
}
cancel() {
this.clear();
this.#deactivate();
}
zoomToFit() {
if (this.#points.length < 2) return;
const bounds = L.latLngBounds(this.#points);
// Use NavigationController padding if available, otherwise fallback
let fitOptions = { maxZoom: 18 };
if (typeof NavigationController !== 'undefined' && NavigationController.mapPadding) {
fitOptions = { ...NavigationController.mapPadding, maxZoom: 18 };
} else {
fitOptions.padding = [50, 50];
}
this.#map.fitBounds(bounds, fitOptions);
// Re-show popup after zoom (fitBounds closes popups during animation)
setTimeout(() => {
if (this.#points.length > 1) {
this.#showDistance();
}
}, 300);
}
clear() {
// Remove rubber band
this.#removeRubberBand();
// Remove all markers
this.#markers.forEach(m => this.#map.removeLayer(m));
this.#markers = [];
// Remove all lines
this.#lines.forEach(l => this.#map.removeLayer(l));
this.#lines = [];
// Close popup
if (this.#popup) {
this.#map.closePopup(this.#popup);
this.#popup = null;
}
// Clear points
this.#points = [];
}
#showDistance() {
if (this.#points.length < 2) return;
const totalDist = this.#calculateDistance();
const lastPoint = this.#points[this.#points.length - 1];
// Format distance
let distStr;
if (totalDist < 1) {
distStr = `${Math.round(totalDist * 1000)} m`;
} else {
distStr = `${totalDist.toFixed(2)} km`;
}
// Add segment count if more than 2 points
const segmentInfo = this.#points.length > 2
? `<div style="font-size: 11px; opacity: 0.8; margin-top: 2px;">${this.#points.length - 1} segments</div>`
: '';
const content = `
<div class="measure-info">
<div style="font-size: 16px; font-weight: 600;">${distStr}</div>
${segmentInfo}
</div>
`;
if (this.#popup) {
this.#popup.setContent(content).setLatLng(lastPoint);
// Must re-open popup in case it was closed by fitBounds
if (!this.#map.hasLayer(this.#popup)) {
this.#popup.openOn(this.#map);
}
} else {
this.#popup = L.popup({
closeButton: false,
className: 'measure-popup',
autoPan: false
})
.setLatLng(lastPoint)
.setContent(content)
.openOn(this.#map);
}
}
#calculateDistance() {
let total = 0;
for (let i = 1; i < this.#points.length; i++) {
const p1 = this.#points[i - 1];
const p2 = this.#points[i];
total += calculateDistanceKm(p1.lat, p1.lng, p2.lat, p2.lng);
}
return total;
}
static isMeasurePopup(popup) {
return popup && popup.options && popup.options.className === 'measure-popup';
}
}
// Bridge functions for HTML onclick and external calls
function toggleMeasureTool() {
if (window.measurementTool) window.measurementTool.toggle();
}
function cancelMeasurement() {
if (window.measurementTool) window.measurementTool.cancel();
}
// ========== Route Search ==========
// State for route search (exposed globally for elevation panel integration)
const routeSearchState = {
from: null, // { lat, lng, name }
to: null, // { lat, lng, name }
activeField: null, // 'from' or 'to'
searchTimeout: null,
waypointSearchTimeouts: {},
routeBounds: null, // Store route bounds for reset view
elevationData: null, // Array of {lat, lng, elevation} from API
elevationStats: null, // {gain, loss, min, max}
extraWaypoints: [], // { lat, lng, name, marker }
mapClickHandler: null,
waypointIdCounter: 0,
countryCode: null,
countryCodeDayKey: null,
countryCodePromise: null,
active: false
};
window.routeSearchState = routeSearchState; // Expose for app.js elevation panel
function activateLocationSearch() {
const popup = document.getElementById('searchPopup');
const inputFrom = document.getElementById('searchFromInput');
if (!popup) return;
// Close transparency popup if open
const transPopup = document.getElementById('transparencySliderPopup');
if (transPopup && transPopup.style.display === 'block') {
closeTransparencyPopup();
}
// Reset position to CSS default (centered via transform)
popup.style.left = '';
popup.style.top = '';
popup.style.transform = '';
// Show the popup (CSS will center it)
popup.style.display = 'block';
routeSearchState.active = true;
if (typeof hideDiaryRoutes === 'function') {
hideDiaryRoutes();
}
// Clear map layers for clean search view (like replay does)
if (window.clearMapLayers) {
window.clearMapLayers();
}
// Enable diary location click mode
enableDiaryLocationClickMode();
setWaypointEnabled(!!routeSearchState.to);
resolveRouteSearchCountryCode().catch(() => {});
// Map click adds waypoint while search is open
if (window.map) {
if (routeSearchState.mapClickHandler) {
window.map.off('click', routeSearchState.mapClickHandler);
}
routeSearchState.mapClickHandler = (e) => {
if (!routeSearchState.to) return;
const lat = e.latlng.lat;
const lng = e.latlng.lng;
const popupHtml = `
<div class="route-waypoint-popup">
<div class="route-waypoint-title">Waypoint</div>
<div class="route-waypoint-coords">${lat.toFixed(5)}, ${lng.toFixed(5)}</div>
<button class="route-waypoint-action" type="button"
onclick="addWaypointFromMap(${lat}, ${lng})">
Add waypoint
</button>
</div>`;
L.popup({ offset: [0, -8] })
.setLatLng([lat, lng])
.setContent(popupHtml)
.openOn(window.map);
};
window.map.on('click', routeSearchState.mapClickHandler);
}
if (inputFrom) {
inputFrom.focus();
}
}
// Enable clicking diary locations to populate search fields
function enableDiaryLocationClickMode() {
// Target diary entries - these are <li> elements containing .location-data spans
const locationDataElements = document.querySelectorAll('.location-data[data-lat][data-lng]');
locationDataElements.forEach(locData => {
const li = locData.closest('li');
if (li && !li._routeClickHandler) {
li.classList.add('route-clickable');
li._routeClickHandler = (e) => {
// Don't interfere if clicking on a link or button
if (e.target.closest('a, button')) return;
e.stopPropagation();
e.preventDefault();
const lat = parseFloat(locData.dataset.lat);
const lng = parseFloat(locData.dataset.lng);
const name = locData.dataset.location || 'Unknown location';
if (!isNaN(lat) && !isNaN(lng)) {
setRouteLocationFromDiary(lat, lng, name);
}
};
li.addEventListener('click', li._routeClickHandler);
}
});
// Also handle Analysis mode location sections
const locationSections = document.querySelectorAll('.location-section');
locationSections.forEach(section => {
const nameEl = section.querySelector('.location-name');
if (nameEl && !nameEl._routeClickHandler) {
nameEl.classList.add('route-clickable');
nameEl._routeClickHandler = (e) => {
e.stopPropagation();
const lat = parseFloat(section.dataset.lat);
const lng = parseFloat(section.dataset.lng);
const name = nameEl.textContent.trim();
if (!isNaN(lat) && !isNaN(lng)) {
setRouteLocationFromDiary(lat, lng, name);
}
};
nameEl.addEventListener('click', nameEl._routeClickHandler);
}
});
}
// Disable diary location click mode
function disableDiaryLocationClickMode() {
// Remove from diary entries
const diaryEntries = document.querySelectorAll('li.route-clickable');
diaryEntries.forEach(li => {
li.classList.remove('route-clickable');
if (li._routeClickHandler) {
li.removeEventListener('click', li._routeClickHandler);
delete li._routeClickHandler;
}
});
// Remove from Analysis mode location names
const locationNames = document.querySelectorAll('.location-name.route-clickable');
locationNames.forEach(nameEl => {
nameEl.classList.remove('route-clickable');
if (nameEl._routeClickHandler) {
nameEl.removeEventListener('click', nameEl._routeClickHandler);
delete nameEl._routeClickHandler;
}
});
}
function closeSearchPopup() {
const popup = document.getElementById('searchPopup');
if (popup) popup.style.display = 'none';
routeSearchState.active = false;
// Clear results but keep selections
document.getElementById('searchResultsFrom')?.replaceChildren();
document.getElementById('searchResultsTo')?.replaceChildren();
// Disable diary location click mode
disableDiaryLocationClickMode();
// Clear any route search markers and layers
if (window.routeSearchLayer && window.map) {
window.map.removeLayer(window.routeSearchLayer);
window.routeSearchLayer = null;
}
if (window.routeSearchMarkerFrom && window.map) {
window.map.removeLayer(window.routeSearchMarkerFrom);
window.routeSearchMarkerFrom = null;
}
if (window.routeSearchMarkerTo && window.map) {
window.map.removeLayer(window.routeSearchMarkerTo);
window.routeSearchMarkerTo = null;
}
if (routeSearchState.extraWaypoints && window.map) {
routeSearchState.extraWaypoints.forEach(wp => {
if (wp.marker) window.map.removeLayer(wp.marker);
});
}
// Restore map to current day view
if (window.showDayMap && window.NavigationController?.dayKey) {
window.showDayMap(window.NavigationController.dayKey);
}
if (typeof showDiaryRoutes === 'function') {
showDiaryRoutes();
}
if (window.map && routeSearchState.mapClickHandler) {
window.map.off('click', routeSearchState.mapClickHandler);
routeSearchState.mapClickHandler = null;
}
}
window.closeSearchPopup = closeSearchPopup; // Expose for app.js to close when returning to import screen
function clearRouteSearch() {
routeSearchState.from = null;
routeSearchState.to = null;
const inputFrom = document.getElementById('searchFromInput');
const inputTo = document.getElementById('searchToInput');
const resultsFrom = document.getElementById('searchResultsFrom');
const resultsTo = document.getElementById('searchResultsTo');
const btnRoute = document.getElementById('btnGetRoute');
if (inputFrom) {
inputFrom.value = '';
inputFrom.classList.remove('has-selection');
}
if (inputTo) {
inputTo.value = '';
inputTo.classList.remove('has-selection');
}
if (resultsFrom) resultsFrom.replaceChildren();
if (resultsTo) resultsTo.replaceChildren();
if (btnRoute) btnRoute.disabled = true;
// Hide navigation controls
const btnReset = document.getElementById('btnResetView');
const waypointDropdown = document.getElementById('waypointDropdown');
if (btnReset) btnReset.style.display = 'none';
if (waypointDropdown) waypointDropdown.style.display = 'none';
setWaypointEnabled(false);
clearWaypointFields();
setRouteSearchInfo(null);
routeSearchState.countryCode = null;
routeSearchState.countryCodeDayKey = null;
routeSearchState.countryCodePromise = null;
// Clear route bounds and elevation data
routeSearchState.routeBounds = null;
routeSearchState.elevationData = null;
routeSearchState.elevationStats = null;
// Clear any existing route on map (map is global from app.js)
if (window.map) {
removeRouteSearchPolylines();
removeRouteSearchMarkers();
window.map.closePopup();
}
if (window.routeSearchLayer && window.map) {
window.map.removeLayer(window.routeSearchLayer);
window.routeSearchLayer = null;
}
if (window.routeSearchMarkerFrom && window.map) {
window.map.removeLayer(window.routeSearchMarkerFrom);
window.routeSearchMarkerFrom = null;
}
if (window.routeSearchMarkerTo && window.map) {
window.map.removeLayer(window.routeSearchMarkerTo);
window.routeSearchMarkerTo = null;
}
if (routeSearchState.extraWaypoints && window.map) {
routeSearchState.extraWaypoints.forEach(wp => {
if (wp.marker) window.map.removeLayer(wp.marker);
});
}
// Clear waypoints after markers removed
routeSearchState.waypoints = [];
routeSearchState.extraWaypoints = [];
}
function addWaypointFieldFromButton() {
if (!routeSearchState.to) return;
addWaypointField();
}
window.addWaypointFieldFromButton = addWaypointFieldFromButton;
function onSearchFocus(field) {
routeSearchState.activeField = field;
// Hide the other results
const results = ['from', 'to'].filter(f => f !== field)
.map(f => document.getElementById(f === 'from' ? 'searchResultsFrom' : 'searchResultsTo'));
results.forEach(r => r && r.replaceChildren());
document.querySelectorAll('[id^="searchResultsWaypoint-"]').forEach(el => el.replaceChildren());
}
function onSearchInput(field) {
routeSearchState.activeField = field;
const input = document.getElementById(field === 'from' ? 'searchFromInput' : 'searchToInput');
const resultsDiv = document.getElementById(field === 'from' ? 'searchResultsFrom' : 'searchResultsTo');
if (!input || !resultsDiv) return;
const query = input.value.trim();
// Clear previous timeout
if (routeSearchState.searchTimeout) {
clearTimeout(routeSearchState.searchTimeout);
}
if (query.length < 2) {
resultsDiv.replaceChildren();
return;
}
// Debounce search
routeSearchState.searchTimeout = setTimeout(() => {
performRouteSearch(query, field);
}, 300);
}
async function performRouteSearch(query, field) {
const resultsDiv = document.getElementById(field === 'from' ? 'searchResultsFrom' : 'searchResultsTo');
if (!resultsDiv) return;
try {
const mapboxToken = localStorage.getItem('arc_mapbox_token');
const countryCode = await resolveRouteSearchCountryCode();
const results = await geocodeSearch(query, { provider: mapboxToken ? 'mapbox' : 'nominatim', countryCode });
if (results.length === 0) {
renderSearchStatus(resultsDiv, 'No results found');
return;
}
renderLocationSearchResults(resultsDiv, results, (result) => {
selectRouteLocation(field, result.lat, result.lng, result.name || 'Unknown');
});
} catch (err) {
console.error('Search error:', err);
renderSearchStatus(resultsDiv, 'Search failed');
}
}
async function geocodeSearch(query, { provider, countryCode }) {
if (provider === 'mapbox') {
const mapboxToken = localStorage.getItem('arc_mapbox_token');
if (!mapboxToken) return [];
const buildMapboxUrl = (code) => {
let url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(query)}.json?limit=5&access_token=${mapboxToken}`;
if (code) url += `&country=${code.toUpperCase()}`;
if (window.map) {
const center = window.map.getCenter();
url += `&proximity=${center.lng},${center.lat}`;
}
return url;
};
const mapboxFetch = async (code) => {
const response = await fetch(buildMapboxUrl(code));
const data = await response.json();
const features = Array.isArray(data.features) ? data.features : [];
return features.map(f => {
const name = f.place_name.split(',').slice(0, 2).join(',');
return { name, lat: f.center[1], lng: f.center[0] };
});
};
let results = [];
try {
results = await mapboxFetch(countryCode);
} catch (_) {
results = [];
}
if (results.length === 0 && countryCode) {
try {
results = await mapboxFetch(null);
} catch (_) {
results = [];
}
}
if (results.length > 0) return results;
}
// Nominatim fallback
const buildNominatimUrl = (code) => {
let url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5`;
if (code) url += `&countrycodes=${code.toLowerCase()}`;
if (window.map) {
const bounds = window.map.getBounds();
const sw = bounds.getSouthWest();
const ne = bounds.getNorthEast();
url += `&viewbox=${sw.lng},${ne.lat},${ne.lng},${sw.lat}&bounded=0`;
}
return url;
};
const nominatimFetch = async (code) => {
const response = await fetch(buildNominatimUrl(code), { headers: { 'User-Agent': 'ArcTimelineReader/1.0' } });
const results = await response.json();
return results.map(r => {
const name = r.display_name.split(',').slice(0, 2).join(',');
return { name, lat: parseFloat(r.lat), lng: parseFloat(r.lon) };
});
};
let fallbackResults = [];
try {
fallbackResults = await nominatimFetch(countryCode);
} catch (_) {
fallbackResults = [];
}
if (fallbackResults.length === 0 && countryCode) {
try {
fallbackResults = await nominatimFetch(null);
} catch (_) {
fallbackResults = [];
}
}
return fallbackResults;
}
function selectRouteLocation(field, lat, lng, name) {
routeSearchState[field] = { lat, lng, name };
const input = document.getElementById(field === 'from' ? 'searchFromInput' : 'searchToInput');
const resultsDiv = document.getElementById(field === 'from' ? 'searchResultsFrom' : 'searchResultsTo');
const btnRoute = document.getElementById('btnGetRoute');
if (input) {
input.value = name;
input.classList.add('has-selection');
}
if (resultsDiv) resultsDiv.replaceChildren();
// Enable Go button if From is selected (with or without To)
if (btnRoute) {
btnRoute.disabled = !routeSearchState.from;
}
if (field === 'to') {
setWaypointEnabled(true);
}
// Auto-focus the other field if empty
if (field === 'from' && !routeSearchState.to) {
document.getElementById('searchToInput')?.focus();
}
}
function addWaypoint(lat, lng, name, waypointId) {
if (!window.map) return;
const draggable = !!routeSearchState.to;
const marker = L.marker([lat, lng], {
icon: L.divIcon({
className: 'route-marker-waypoint',
html: `<div class="route-marker-pin waypoint"><div class="pin-icon"><span>W</span></div></div>`,
iconSize: [32, 40],
iconAnchor: [16, 40]
}),
draggable
}).addTo(window.map).bindPopup(`<b>Waypoint:</b> ${name}`, { offset: [0, -35] });
marker._routeSearchMarker = true;
const wpId = waypointId || `wp-${++routeSearchState.waypointIdCounter}`;
const waypoint = { id: wpId, lat, lng, name, marker, label: 'W' };
routeSearchState.extraWaypoints.push(waypoint);
marker.on('dragend', () => {
const pos = marker.getLatLng();
waypoint.lat = pos.lat;
waypoint.lng = pos.lng;
if (waypoint.name && waypoint.name.startsWith('Waypoint (')) {
waypoint.name = `Waypoint (${pos.lat.toFixed(5)}, ${pos.lng.toFixed(5)})`;
const input = document.getElementById(`searchWaypointInput-${wpId}`);
if (input) input.value = waypoint.name;
}
if (waypoint.marker) {
waypoint.marker.setPopupContent(`<b>Waypoint:</b> ${waypoint.name}`);
}
populateWaypointSelect();
maybeRerouteAfterWaypoint();
});
populateWaypointSelect();
maybeRerouteAfterWaypoint();
}
function addWaypointFromMap(lat, lng) {
if (window.map) {
window.map.closePopup();
}
const name = `Waypoint (${lat.toFixed(5)}, ${lng.toFixed(5)})`;
const wpId = addWaypointField(name);
addWaypoint(lat, lng, name, wpId);
}
window.addWaypointFromMap = addWaypointFromMap;
function addWaypointField(initialValue) {
const container = document.getElementById('searchWaypointsContainer');
const group = document.getElementById('searchWaypointsGroup');
if (!container || !group) return null;
group.style.display = 'block';
const id = `wp-${++routeSearchState.waypointIdCounter}`;
const item = document.createElement('div');
item.className = 'waypoint-item';
item.dataset.id = id;
const handle = document.createElement('span');
handle.className = 'waypoint-handle';
handle.setAttribute('draggable', 'true');
const fieldWrap = document.createElement('div');
fieldWrap.className = 'search-field waypoint-field';
fieldWrap.innerHTML = `
<label for="searchWaypointInput-${id}">Waypoint:</label>
<input type="text" id="searchWaypointInput-${id}" placeholder="Search waypoint..." oninput="onWaypointInput('${id}')" onfocus="onWaypointFocus('${id}')">
<div class="search-results" id="searchResultsWaypoint-${id}"></div>
`;
const deleteBtn = document.createElement('button');
deleteBtn.className = 'waypoint-delete';
deleteBtn.type = 'button';
deleteBtn.textContent = '×';
deleteBtn.title = 'Remove waypoint';