-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloopify.js
More file actions
1657 lines (1408 loc) · 55.8 KB
/
loopify.js
File metadata and controls
1657 lines (1408 loc) · 55.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
// Instance Variables
let map, userLocationCircle, routingControl;
let currentUnit = 'mi';
let kmConstant = 1.60934;
let waypoints = [];
let targetDistance = 0;
let currentDistance = 0;
let currentElevation = 0;
let quotes = [];
let OPENROUTE_API_KEY = "";
let markers = [];
let autocompleteTimeout;
let isSearching = false;
let originalPosition;
let undoStack = [];
let redoStack = [];
let snappedLatLng = [];
let previousDistance = 0.25 * kmConstant;
let bathroomLayer, trafficLightLayer;
let showTrafficLight = true, showBathroom = true;
let loaded = false;
let satelliteLayer, osmLayer;
let isBathroomLoading = false;
let isTrafficLightLoading = false;
const CACHE_EXPIRATION = 24 * 60 * 60 * 1000;
let isLayerToggling = false;
let isBathroomToggling = false;
let isTrafficLightToggling = false;
// Maps
let bathroomMarkers = new Map();
let trafficLightMarkers = new Map();
let debugBoundingBoxes = [];
let startPoint = null;
let endPoint = null;
function drawBoundingBox(bbox, color) {
const rectangle = L.rectangle(bbox, {
color: color,
weight: 2,
fillOpacity: 0.1
}).addTo(map);
debugBoundingBoxes.push(rectangle);
}
function clearBoundingBoxes() {
debugBoundingBoxes.forEach(rectangle => map.removeLayer(rectangle));
debugBoundingBoxes = [];
}
function unloadFarBoundingBoxes() {
const bounds = map.getBounds();
const center = bounds.getCenter();
const maxDistance = 5000; // Maximum distance in meters to keep bounding boxes
debugBoundingBoxes = debugBoundingBoxes.filter(rectangle => {
const bboxCenter = rectangle.getBounds().getCenter();
const distance = map.distance(center, bboxCenter);
if (distance > maxDistance) {
map.removeLayer(rectangle);
return false;
}
return true;
});
// Check for overlapping bounding boxes
for (let i = 0; i < debugBoundingBoxes.length; i++) {
for (let j = i + 1; j < debugBoundingBoxes.length; j++) {
if (debugBoundingBoxes[i].getBounds().intersects(debugBoundingBoxes[j].getBounds())) {
map.removeLayer(debugBoundingBoxes[j]);
debugBoundingBoxes.splice(j, 1);
j--; // Adjust index after removal
}
}
}
}
function initMap() {
map = L.map('map', {
attributionControl: false,
maxZoom: 18 // Set maximum zoom level
}).setView([0, 0], 13);
var attributionControl = L.control.attribution({
position: 'bottomright',
prefix: ''
}).addTo(map);
attributionControl.addAttribution('© <a href="#" id="creditsLink">Loopify Credits</a>');
osmLayer = L.tileLayer('http://{s}.google.com/vt?lyrs=m&x={x}&y={y}&z={z}', {
maxZoom: 20,
subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
});
osmLayer.addTo(map);
satelliteLayer = L.tileLayer('http://{s}.google.com/vt?lyrs=s,h&x={x}&y={y}&z={z}', {
maxZoom: 20,
subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
});
map.whenReady(() => {
console.log('Map is fully initialized and ready for interactions.');
});
bathroomLayer = L.layerGroup().addTo(map);
trafficLightLayer = L.layerGroup().addTo(map);
promptForLocation();
map.on('zoomend', updateUserLocationCircleSize);
map.on('click', onMapClick);
map.on('zoomend', fetchData);
map.on('moveend', fetchData);
// Initialize Leaflet Routing Machine without default markers
routingControl = L.Routing.control({
waypoints: [],
routeWhileDragging: true,
createMarker: function (i, waypoint, n) {
// Create custom markers using the snapped points
let fillColor;
if (i === 0) {
fillColor = 'green'; // First waypoint
} else if (i === n - 1) {
fillColor = 'red'; // Last waypoint
} else {
fillColor = 'blue'; // Intermediate waypoints
}
return L.marker(waypoint.latLng, {
draggable: true,
icon: L.divIcon({
className: 'custom-circle-marker',
html: `<div style="background-color: ${fillColor}; width: 16px; height: 16px; border-radius: 50%; border: 2px solid black;"></div>`,
iconSize: [16, 16],
iconAnchor: [8, 8]
})
}).on('dragend', function (e) {
const markerIndex = markers.indexOf(e.target);
if (markerIndex !== -1) {
// Save the current state to the undo stack
undoStack.push([...waypoints]);
redoStack = []; // Clear the redo stack
// Snap the dragged marker to the nearest road
const draggedLatLng = e.target.getLatLng();
const [snappedLat, snappedLon] = snapToNearestEdge(draggedLatLng.lat, draggedLatLng.lng);
const snappedPoint = L.latLng(snappedLat, snappedLon);
// Update the marker's position
e.target.setLatLng(snappedPoint);
// Update the waypoint's position in the array
waypoints[markerIndex] = snappedPoint;
// Update the routing machine with the new waypoints
routingControl.setWaypoints(waypoints);
}
});
},
lineOptions: {
styles: [{ color: '#0044cc', weight: 5, opacity: 0.8 }] // Darker blue line
},
show: false // disable the itinerary summary stuff (its ugly)
}).addTo(map);
routingControl.on('routesfound', function (e) {
const routes = e.routes;
if (routes.length > 0) {
const totalDistance = routes[0].summary.totalDistance; // Distance in meters
updateDistanceSummary(totalDistance);
}
});
}
function initFilters() {
bathroomLayer = L.layerGroup().addTo(map);
trafficLightLayer = L.layerGroup().addTo(map);
document.getElementById('showBathrooms').checked = true;
document.getElementById('showTrafficLights').checked = true;
updateObject();
}
function promptForLocation() {
// Uses browser geolocation service
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const {
latitude,
longitude
} = position.coords;
originalPosition = [latitude, longitude];
map.setView(originalPosition, 16);
addUserLocationCircle(originalPosition);
startingNode = {
lat: latitude,
lon: longitude
};
fetchData();
},
(error) => {
console.error('Error getting location:', error);
alert("Unable to get your location. Using default location.");
originalPosition = [51.505, -0.09];
map.setView(originalPosition, 16);
addUserLocationCircle(originalPosition);
startingNode = {
lat: 51.505,
lon: -0.09
};
fetchData();
}
);
} else {
alert("Geolocation is not supported by your browser. Using default location.");
originalPosition = [51.505, -0.09];
map.setView(originalPosition, 18);
addUserLocationCircle(originalPosition);
startingNode = {
lat: 51.505,
lon: -0.09
};
fetchData();
}
}
function addUserLocationCircle(latlng) {
// Controls the user location circle
if (userLocationCircle) {
map.removeLayer(userLocationCircle);
}
const zoom = map.getZoom();
const radius = Math.max(2, zoom - 7);
userLocationCircle = L.circleMarker(latlng, {
color: 'white',
fillColor: '#0031d1',
fillOpacity: 0.8,
radius: radius
}).addTo(map);
}
function updateUserLocationCircleSize() {
// Location circle's scalability
if (userLocationCircle) {
const zoom = map.getZoom();
const radius = Math.max(2, zoom - 7);
userLocationCircle.setRadius(radius);
}
}
// MAY NOT NEED
async function requestAPI() {
// MAY NOT NEED
try {
const response = await fetch('.gitignore/config.json');
OPENROUTE_API_KEY = await response.json();
} catch (error) {
console.error('Error fetching quotes:', error);
}
}
function onMapClick(e) {
// Called when the map is clicked
if (!isSearching && loaded) {
// Snap the clicked point to the nearest road
const [snappedLat, snappedLon] = snapToNearestEdge(e.latlng.lat, e.latlng.lng);
const snappedPoint = L.latLng(snappedLat, snappedLon);
// Add the snapped point as a waypoint
addWaypoint(snappedPoint);
// Update the routing machine with the new waypoints
routingControl.setWaypoints(waypoints);
} else {
console.log('Please wait a second, data is still loading.');
alert('Please wait a second, data is still loading.');
}
}
function addWaypoint(latlng) {
// Save the current state to the undo stack
undoStack.push([...waypoints]);
redoStack = []; // Clear the redo stack
// Snap the clicked point to the nearest road
const [snappedLat, snappedLon] = snapToNearestEdge(latlng.lat, latlng.lng);
const snappedPoint = L.latLng(snappedLat, snappedLon);
// Add the snapped point to the waypoints array
waypoints.push(snappedPoint);
// Determine the color of the marker based on its position in the route
let fillColor;
if (waypoints.length === 1) {
fillColor = 'green'; // First waypoint
} else if (waypoints.length === waypoints.length) {
fillColor = 'red'; // Last waypoint
} else {
fillColor = 'blue'; // Intermediate waypoints
}
// Add a draggable marker styled as a circle
const marker = L.marker(snappedPoint, {
draggable: true,
icon: L.divIcon({
className: 'custom-circle-marker',
html: `<div style="background-color: ${fillColor}; width: 16px; height: 16px; border-radius: 50%; border: 2px solid black;"></div>`,
iconSize: [16, 16],
iconAnchor: [8, 8]
})
}).addTo(map);
// Handle drag events
marker.on('dragend', function (e) {
console.log('Dragend event triggered for marker:', e.target);
const markerIndex = markers.indexOf(e.target); // Find the index of the dragged marker
console.log('Dragging ended. Marker index:', markerIndex);
if (markerIndex !== -1) {
// Save the current state to the undo stack
undoStack.push([...waypoints]);
redoStack = []; // Clear the redo stack
console.log('Undo stack updated:', undoStack);
// Snap the dragged marker to the nearest road
const draggedLatLng = e.target.getLatLng();
console.log('Dragged marker position:', draggedLatLng);
const [snappedLat, snappedLon] = snapToNearestEdge(draggedLatLng.lat, draggedLatLng.lng);
const snappedPoint = L.latLng(snappedLat, snappedLon);
console.log('Snapped marker position:', snappedPoint);
// Remove the old marker from the map and the markers array
console.log('Removing old marker:', e.target);
map.removeLayer(e.target); // Remove the old marker from the map
markers.splice(markerIndex, 1); // Remove the old marker from the markers array
console.log('Markers array after removal:', markers);
// Add the updated marker to the map and markers array
const updatedMarker = L.marker(snappedPoint, {
draggable: true,
icon: L.divIcon({
className: 'custom-circle-marker',
html: `<div style="background-color: blue; width: 16px; height: 16px; border-radius: 50%; border: 2px solid black;"></div>`,
iconSize: [16, 16],
iconAnchor: [8, 8]
})
}).addTo(map);
console.log('Added updated marker:', updatedMarker);
// Add dragend event to the updated marker
updatedMarker.on('dragend', function (e) {
console.log('Updated marker dragged again.');
marker.on('dragend', e);
});
// Update the waypoint's position in the array
waypoints[markerIndex] = snappedPoint;
console.log('Waypoints array after update:', waypoints);
// Add the updated marker to the markers array
markers.splice(markerIndex, 0, updatedMarker);
console.log('Markers array after adding updated marker:', markers);
// Update the routing machine with the new waypoints
routingControl.setWaypoints(waypoints);
console.log('Routing machine updated with new waypoints.');
// Ensure no duplicate markers exist
updateMarkerColors();
console.log('Marker colors updated.');
} else {
console.log('Marker not found in the markers array.');
}
});
// Store the marker for future reference
markers.push(marker);
// Update the colors of all markers to ensure the first is green, the last is red, and others are blue
updateMarkerColors();
// Update the routing machine with the new waypoints
routingControl.setWaypoints(waypoints);
}
function updateMarkerColors() {
markers.forEach((marker, index) => {
let fillColor;
if (index === 0) {
fillColor = 'green'; // First waypoint
} else if (index === markers.length - 1) {
fillColor = 'red'; // Last waypoint
} else {
fillColor = 'blue'; // Intermediate waypoints
}
const icon = L.divIcon({
className: 'custom-circle-marker',
html: `<div style="background-color: ${fillColor}; width: 16px; height: 16px; border-radius: 50%; border: 2px solid black;"></div>`,
iconSize: [16, 16],
iconAnchor: [8, 8]
});
marker.setIcon(icon);
});
}
function snapToNearestEdge(lat, lon) {
let nearestEdge = null;
let minDistance = Infinity;
let nearestPoint = [lat, lon];
Object.values(graph.edges).forEach(edgeList => {
edgeList.forEach(edge => {
const fromNode = graph.nodes[edge.from];
const toNode = graph.nodes[edge.to];
if (fromNode && toNode) {
const edgePoint = findNearestPointOnSegment(
lat, lon,
fromNode.lat, fromNode.lon,
toNode.lat, toNode.lon
);
const distance = haversineDistance(lat, lon, edgePoint[0], edgePoint[1]);
if (distance < minDistance) {
minDistance = distance;
nearestEdge = edge;
nearestPoint = edgePoint;
}
}
});
});
return nearestPoint;
}
function findNearestPointOnSegment(px, py, x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
if (dx === 0 && dy === 0) {
return [x1, y1];
}
const t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy);
// Edge cases
if (t < 0) {
return [x1, y1];
}
if (t > 1) {
return [x2, y2];
}
return [x1 + t * dx, y1 + t * dy];
}
function updateDistanceAndElevation() {
// self explanatory
currentDistance = calculateTotalDistance();
currentElevation = calculateMockElevation(currentDistance);
updateDistanceDisplay();
updateElevationDisplay();
}
function updateDistanceSummary(distanceInMeters) {
const actualDistanceElement = document.getElementById('actualDistance');
let displayDistance;
if (currentUnit === 'km') {
displayDistance = distanceInMeters / 1000; // Convert meters to kilometers
actualDistanceElement.textContent = `Distance: ${displayDistance.toFixed(2)} km`;
} else {
displayDistance = distanceInMeters / 1609.34; // Convert meters to miles
actualDistanceElement.textContent = `Distance: ${displayDistance.toFixed(2)} mi`;
}
}
function calculateTotalDistance() {
let totalDistance = 0;
for (let i = 1; i < waypoints.length; i++) {
totalDistance += waypoints[i - 1].distanceTo(waypoints[i]);
}
return totalDistance;
}
function updateDistanceDisplay() {
const actualDistanceElement = document.getElementById('actualDistance');
let displayDistance;
if (currentUnit === 'km') {
displayDistance = currentDistance / 1000;
actualDistanceElement.textContent = `Distance: ${displayDistance.toFixed(2)} km`;
} else {
displayDistance = currentDistance / 1609.34;
actualDistanceElement.textContent = `Distance: ${displayDistance.toFixed(2)} mi`;
}
}
function updateElevationDisplay() {
const elevationElement = document.getElementById('elevation');
if (currentUnit === 'km') {
elevationElement.textContent = `Elevation: ${currentElevation.toFixed(0)} m`;
} else {
const elevationFt = currentElevation * 3.28084;
elevationElement.textContent = `Elevation: ${elevationFt.toFixed(0)} ft`;
}
}
function calculateMockElevation(distance) { // NEED TO APPLY AN API FOR THIS
return Math.floor(distance / 100);
}
function toggleUnit(unit) {
currentUnit = unit;
document.querySelectorAll('.unit-option').forEach(option => {
option.classList.toggle('active', option.dataset.unit === unit);
});
const slider = document.querySelector('.unit-slider');
slider.style.transform = unit === 'km' ? 'translateX(calc(100% + 8px))' : 'translateX(0)';
updateDistanceDisplay();
updateElevationDisplay();
}
function toggleFullscreen() {
const mapElement = document.getElementById('map');
if (!document.fullscreenElement) {
if (mapElement.requestFullscreen) {
mapElement.requestFullscreen();
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}
function relocateToOriginalPosition() {
if (originalPosition) {
map.setView(originalPosition, 17);
addUserLocationCircle(originalPosition);
}
}
async function fetchQuotes() {
try {
const response = await fetch('./quotes/RunningQuote.json');
quotes = await response.json();
displayRandomQuote();
} catch (error) {
console.error('Error fetching quotes:', error);
}
}
function displayRandomQuote() {
if (quotes.length === 0) return;
const randomIndex = Math.floor(Math.random() * quotes.length);
const randomQuote = quotes[randomIndex];
document.getElementById('quote').textContent = `"${randomQuote.quote}"`;
document.getElementById('author').textContent = `- ${randomQuote.author}`;
}
function getQuote(index) {
if (quotes.length === 0) return;
const quote = quotes[index];
document.getElementById('quote').textContent = `"${quote.quote}"`;
document.getElementById('author').textContent = `- ${quote.author}`;
}
function clearRoute() {
// Clear waypoints and markers
waypoints = [];
markers.forEach(marker => map.removeLayer(marker));
markers = [];
// Clear the routing machine
routingControl.setWaypoints([]);
// Clear the map information stuff
if (currentUnit === 'km') {
document.getElementById('actualDistance').textContent = 'Distance: 0.00 km';
} else {
document.getElementById('actualDistance').textContent = 'Distance: 0.00 mi';
}
}
function searchLocation() {
const query = document.getElementById('searchInput').value;
if (query.length < 3) return;
fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => {
const autocompleteResults = document.getElementById('autocompleteResults');
autocompleteResults.innerHTML = '';
if (data.length === 0) {
const noResults = document.createElement('div');
noResults.className = 'no-results';
noResults.textContent = 'No location found';
autocompleteResults.appendChild(noResults);
} else {
data.slice(0, 5).forEach(result => {
const item = document.createElement('div');
item.className = 'autocomplete-item';
item.textContent = result.display_name;
item.addEventListener('click', () => selectLocation(result));
autocompleteResults.appendChild(item);
});
}
autocompleteResults.style.display = 'block';
})
.catch(error => {
console.error('Error:', error);
const autocompleteResults = document.getElementById('autocompleteResults');
autocompleteResults.innerHTML = '';
const errorMessage = document.createElement('div');
errorMessage.className = 'no-results';
errorMessage.textContent = 'Error searching for location';
autocompleteResults.appendChild(errorMessage);
autocompleteResults.style.display = 'block';
});
}
function selectLocation(location) {
const latlng = L.latLng(parseFloat(location.lat), parseFloat(location.lon));
map.setView(latlng, 18);
addWaypoint(latlng);
document.getElementById('autocompleteResults').style.display = 'none';
document.getElementById('searchInput').value = location.display_name;
isSearching = false;
}
function undo() {
if (undoStack.length > 0) {
redoStack.push([...waypoints]);
waypoints = undoStack.pop();
updateRouteAndMarkers();
routingControl.setWaypoints(waypoints);
}
}
function redo() {
if (redoStack.length > 0) {
undoStack.push([...waypoints]);
waypoints = redoStack.pop();
updateRouteAndMarkers();
routingControl.setWaypoints(waypoints);
}
}
function updateRouteAndMarkers() {
// Remove ALL existing markers from the map
for (let i = markers.length - 1; i >= 0; i--) {
if (markers[i]) {
map.removeLayer(markers[i]);
}
}
// Clear the markers array
markers = [];
// Add new markers for each waypoint
waypoints.forEach((latlng, index) => {
// Create marker code...
// Make sure to use the onDragEnd function defined above
marker.on('dragend', onDragEnd);
markers.push(marker);
});
// Update the routing
routingControl.setWaypoints(waypoints);
}
const EARTH_RADIUS = 6371; // km
function haversineDistance(lat1, lon1, lat2, lon2) {
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * 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(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c;
}
function getBoundingBox(lat, lon, distance) {
if (currentUnit === 'mi') {
distance *= kmConstant; // Convert miles to kilometers
}
const EARTH_RADIUS = 6371; // Earth's radius in kilometers
const latChange = (distance / EARTH_RADIUS) * (180 / Math.PI);
const lonChange = (distance / (EARTH_RADIUS * Math.cos(lat * Math.PI / 180))) * (180 / Math.PI);
const boundingBox = [
[lat - latChange, lon - lonChange], // Bottom-left (south-west)
[lat + latChange, lon + lonChange] // Top-right (north-east)
];
const topLeft = [lat + latChange, lon - lonChange];
const topRight = [lat + latChange, lon + lonChange];
// Call the haversineDistance function to calculate distance between top-left and top-right
const distanceTopLeftToTopRight = haversineDistance(topLeft[0], topLeft[1], topRight[0], topRight[1]);
console.log("Distance between Top-Left and Top-Right: ", distanceTopLeftToTopRight.toFixed(2), "km");
return boundingBox;
}
// This is the filters dropdown code
function toggleDropdown() {
const optionsContainer = document.getElementById('optionsContainer');
optionsContainer.classList.toggle('show');
}
async function loadBathrooms() {
isBathroomLoading = true;
const bounds = map.getBounds();
const cacheKey = `bathrooms_${bounds.getSouth()}_${bounds.getWest()}_${bounds.getNorth()}_${bounds.getEast()}`;
const cachedData = localStorage.getItem(cacheKey);
const startTime = performance.now();
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData);
if (Date.now() - timestamp < CACHE_EXPIRATION) {
console.log("Using cached bathroom data");
bathrooms = data;
}
} else {
const url = `https://overpass-api.de/api/interpreter?data=[out:json];node["amenity"="toilets"](${bounds.getSouth()},${bounds.getWest()},${bounds.getNorth()},${bounds.getEast()});out;`;
console.log('Fetching bathrooms:', url);
bathrooms = await fetchAndFilterObjects(url, './assets/Bathroom.png');
// Cache the fetched data
localStorage.setItem(cacheKey, JSON.stringify({ data: bathrooms, timestamp: Date.now() }));
}
const endTime = performance.now();
console.log(`Bathrooms loaded in ${(endTime - startTime).toFixed(2)} ms`);
updateMarkers(bathrooms, bathroomMarkers, bathroomLayer, 'Bathroom');
isBathroomLoading = false;
}
async function loadTrafficLights() {
isTrafficLightLoading = true;
const bounds = map.getBounds();
const cacheKey = `lights_${bounds.getSouth()}_${bounds.getWest()}_${bounds.getNorth()}_${bounds.getEast()}`;
const cachedData = localStorage.getItem(cacheKey);
const startTime = performance.now();
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData);
if (Date.now() - timestamp < CACHE_EXPIRATION) {
console.log("Using cached traffic light data");
lights = data;
}
} else {
const url = `https://overpass-api.de/api/interpreter?data=[out:json];node["highway"="traffic_signals"](${bounds.getSouth()},${bounds.getWest()},${bounds.getNorth()},${bounds.getEast()});out;`;
console.log('Fetching traffic lights:', url);
lights = await fetchAndFilterObjects(url, './assets/TrafficLight.png');
// Cache the fetched data
localStorage.setItem(cacheKey, JSON.stringify({ data: lights, timestamp: Date.now() }));
}
const endTime = performance.now();
console.log(`Traffic lights loaded in ${(endTime - startTime).toFixed(2)} ms`);
updateMarkers(lights, trafficLightMarkers, trafficLightLayer, 'TrafficLight');
isTrafficLightLoading = false;
}
async function fetchAndFilterObjects(url, iconPath) {
const response = await fetch(url);
const data = await response.json();
return filterObjects(data.elements, iconPath);
}
function filterObjects(objects, iconPath) {
const thresholdDistance = 100; // meters
const filteredObjects = [];
objects.forEach(object => {
if (!filteredObjects.some(filteredObject =>
haversineDistance(filteredObject.lat, filteredObject.lon, object.lat, object.lon) *
1000 < thresholdDistance
)) {
filteredObjects.push(object);
}
});
return filteredObjects;
}
async function fetchRoadData(bbox) {
const query = `
[out:json];
(
way["highway"](${bbox[0][0]},${bbox[0][1]},${bbox[1][0]},${bbox[1][1]});
node(w);
);
out body;
>;
out skel qt;
`;
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: query
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const graph = {
nodes: {},
edges: {}
};
// Process all nodes
data.elements.forEach(element => {
if (element.type === 'node') {
graph.nodes[element.id] = {
id: element.id,
lat: element.lat,
lon: element.lon
};
}
});
// Process all ways
data.elements.forEach(element => {
if (element.type === 'way' && element.tags && element.tags.highway) {
for (let i = 1; i < element.nodes.length; i++) {
const fromId = element.nodes[i - 1];
const toId = element.nodes[i];
if (graph.nodes[fromId] && graph.nodes[toId]) {
const fromNode = graph.nodes[fromId];
const toNode = graph.nodes[toId];
const distance = haversineDistance(fromNode.lat, fromNode.lon, toNode
.lat,
toNode.lon);
if (!graph.edges[fromId]) graph.edges[fromId] = [];
if (!graph.edges[toId]) graph.edges[toId] = [];
graph.edges[fromId].push({
from: fromId,
to: toId,
distance,
name: element.tags.name || '',
highway: element.tags.highway
});
graph.edges[toId].push({
from: toId,
to: fromId,
distance,
name: element.tags.name || '',
highway: element.tags.highway
});
}
}
}
});
return graph;
}
async function fetchRoadDataWithRateLimit(bbox, retries = 3) {
const query = `
[out:json];
(
way["highway"](${bbox[0][0]},${bbox[0][1]},${bbox[1][0]},${bbox[1][1]});
node(w);
);
out body;
>;
out skel qt;
`;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: query
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
const graph = {
nodes: {},
edges: {}
};
// Process all nodes
data.elements.forEach(element => {
if (element.type === 'node') {
graph.nodes[element.id] = {
id: element.id,
lat: element.lat,
lon: element.lon
};
}
});
// Process all ways
data.elements.forEach(element => {
if (element.type === 'way' && element.tags && element.tags.highway) {
for (let i = 1; i < element.nodes.length; i++) {
const fromId = element.nodes[i - 1];
const toId = element.nodes[i];
if (graph.nodes[fromId] && graph.nodes[toId]) {
const fromNode = graph.nodes[fromId];
const toNode = graph.nodes[toId];
const distance = haversineDistance(fromNode.lat, fromNode.lon, toNode.lat, toNode.lon);
if (!graph.edges[fromId]) graph.edges[fromId] = [];
if (!graph.edges[toId]) graph.edges[toId] = [];
graph.edges[fromId].push({
from: fromId,
to: toId,
distance,
name: element.tags.name || '',
highway: element.tags.highway
});
graph.edges[toId].push({
from: toId,
to: fromId,
distance,
name: element.tags.name || '',
highway: element.tags.highway
});
}
}
}
});
return graph;
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error.message || error);
if (attempt === retries) {
throw new Error('Failed to fetch road data after multiple attempts.');
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
function visualizeData() {
if (!graph) {
console.error('No graph data available. Please fetch data first.');
return;
}
if (boundingBoxLayer) map.removeLayer(boundingBoxLayer);
if (nodesLayer) map.removeLayer(nodesLayer);
if (edgesLayer) map.removeLayer(edgesLayer);
const distance = parseFloat(document.getElementById('distanceInput').value);
let center;
if (startingNode) {
center = L.latLng(startingNode.lat, startingNode.lon);
} else if (userLocationCircle) {
center = userLocationCircle.getLatLng();
} else {
center = map.getCenter();
}
const bbox = getBoundingBox(center.lat, center.lng, distance);
boundingBoxLayer = L.rectangle(bbox, {
color: 'blue',
weight: 2,
fillOpacity: 0.1
}).addTo(map);
nodesLayer = L.layerGroup().addTo(map);
Object.values(graph.nodes).forEach(node => {
L.circleMarker([node.lat, node.lon], {
radius: 3,
color: 'green',
fillOpacity: 1
}).addTo(nodesLayer);
});