-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathallcode.txt
More file actions
1248 lines (1121 loc) · 45.9 KB
/
Copy pathallcode.txt
File metadata and controls
1248 lines (1121 loc) · 45.9 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
// Places.jsx
import React, { useState, useEffect, useRef } from 'react';
import { useMap } from 'react-leaflet';
import L from 'leaflet';
const Places = ({ visible, userLocation, placeType }) => {
const map = useMap();
const [places, setPlaces] = useState([]);
const placesLayerRef = useRef(null);
// const placeQueries = {
// hospital: { tags: [{ key: "amenity", values: ["hospital"] }], icon: "🏥", color: "#FF5733" },
// restaurant: { tags: [{ key: "amenity", values: ["restaurant", "fast_food"] }], icon: "🍽️", color: "#FF5733" },
// pharmacy: { tags: [{ key: "amenity", values: ["pharmacy"] }], icon: "💊", color: "#1ABC9C" },
// hotel: { tags: [{ key: "tourism", values: ["hotel"] }], icon: "🏨", color: "#8E44AD" },
// atm: { tags: [{ key: "amenity", values: ["atm"] }], icon: "💰", color: "#2ECC71" }
// };
const placeQueries = {
hospital: { tags: [{ key: "amenity", values: ["hospital"] }, { key: "healthcare", values: ["hospital"] }, { key: "building", values: ["hospital"] }], icon: "🏥", color: "#FF5733" },
restaurant: { tags: [{ key: "amenity", values: ["restaurant", "fast_food", "cafe", "food_court"] }], icon: "🍽️", color: "#FF5733" },
cafe: { tags: [{ key: "amenity", values: ["cafe"] }], icon: "☕", color: "#8B4513" },
shop: { tags: [{ key: "shop", values: ["supermarket", "convenience", "mall", "department_store"] }], icon: "🛒", color: "#3498DB" },
atm: { tags: [{ key: "amenity", values: ["atm"] }, { key: "atm", values: ["yes"] }], icon: "💰", color: "#2ECC71" },
bank: { tags: [{ key: "amenity", values: ["bank"] }], icon: "🏦", color: "#9B59B6" },
school: { tags: [{ key: "amenity", values: ["school"] }, { key: "building", values: ["school"] }], icon: "🏫", color: "#F1C40F" },
college: { tags: [{ key: "amenity", values: ["college", "university"] }], icon: "🎓", color: "#E74C3C" },
park: { tags: [{ key: "leisure", values: ["park", "garden"] }], icon: "🌳", color: "#27AE60" },
pharmacy: { tags: [{ key: "amenity", values: ["pharmacy"] }, { key: "shop", values: ["pharmacy"] }], icon: "💊", color: "#1ABC9C" },
cinema: { tags: [{ key: "amenity", values: ["cinema"] }], icon: "🎬", color: "#34495E" },
gym: { tags: [{ key: "leisure", values: ["fitness_centre"] }, { key: "amenity", values: ["gym"] }], icon: "🏋️", color: "#F39C12" },
gas_station: { tags: [{ key: "amenity", values: ["fuel"] }], icon: "⛽", color: "#D35400" },
hotel: { tags: [{ key: "tourism", values: ["hotel", "motel", "hostel"] }], icon: "🏨", color: "#8E44AD" },
police: { tags: [{ key: "amenity", values: ["police"] }], icon: "👮", color: "#2C3E50" },
post_office: { tags: [{ key: "amenity", values: ["post_office"] }], icon: "📮", color: "#E67E22" },
bus_stop: { tags: [{ key: "highway", values: ["bus_stop"] }], icon: "🚏", color: "#16A085" },
parking: { tags: [{ key: "amenity", values: ["parking"] }], icon: "🅿️", color: "#3498DB" },
library: { tags: [{ key: "amenity", values: ["library"] }], icon: "📚", color: "#7F8C8D" }
};
useEffect(() => {
if (!placesLayerRef.current) {
placesLayerRef.current = L.layerGroup().addTo(map);
}
if (!visible) {
placesLayerRef.current.clearLayers();
}
}, [map, visible]);
useEffect(() => {
if (visible && placeType && userLocation) {
fetchPlaces(placeType, userLocation[0], userLocation[1]);
}
}, [visible, userLocation, placeType]);
const buildOverpassQuery = (placeType, lat, lng) => {
if (!placeQueries[placeType]) return null;
const latRadius = 0.145;
const lngRadius = 0.145 / Math.cos((lat * Math.PI) / 180);
const bbox = `${lat - latRadius},${lng - lngRadius},${lat + latRadius},${lng + lngRadius}`;
const tags = placeQueries[placeType].tags;
let queryParts = [];
for (const tag of tags) {
for (const value of tag.values) {
queryParts.push(`node["${tag.key}"="${value}"](${bbox});`);
}
}
return `[out:json];(${queryParts.join('\n')});out body;>;out skel qt;`;
};
const fetchPlaces = async (placeType, lat, lng) => {
placesLayerRef.current.clearLayers();
const query = buildOverpassQuery(placeType, lat, lng);
if (!query) return;
try {
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: query
});
const data = await response.json();
processPlaceData(data, lat, lng, placeType);
} catch (err) {
console.error(`Error fetching ${placeType}:`, err);
}
};
const processPlaceData = (data, lat, lng, placeType) => {
const placeConfig = placeQueries[placeType];
const latlngs = [];
data.elements.forEach(el => {
if (el.type === 'node' && el.lat && el.lon) {
const marker = L.marker([el.lat, el.lon], {
icon: L.divIcon({
html: `<div style="background-color:${placeConfig.color};width:28px;height:28px;border-radius:50%;color:white;font-size:14px;display:flex;align-items:center;justify-content:center;">${placeConfig.icon}</div>`,
iconSize: [28, 28]
})
});
marker.bindPopup(el.tags?.name || `Unnamed ${placeType}`);
marker.addTo(placesLayerRef.current);
latlngs.push([el.lat, el.lon]);
}
});
if (latlngs.length) {
map.fitBounds(L.latLngBounds(latlngs), { padding: [50, 50], maxZoom: 15 });
}
setPlaces(data.elements);
};
return null;
};
export default Places;
//MapView.jsx
import React, { useEffect, useState, useCallback } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap, ZoomControl } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import "leaflet-routing-machine";
import Places from "./Map/Places";
const MapController = ({ setProcessVoiceCommand, updateDirectionsData }) => {
const map = useMap();
const [routingControl, setRoutingControl] = useState(null);
const [currentLocation, setCurrentLocation] = useState(null);
const [placeType, setPlaceType] = useState(null);
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setCurrentLocation([latitude, longitude]);
map.setView([latitude, longitude], 13);
},
(error) => console.error("Error getting location:", error)
);
}
}, [map]);
const createCustomRoutingControl = useCallback((waypoints) => {
if (routingControl) routingControl.remove();
const newRoutingControl = L.Routing.control({
waypoints,
show: false,
plan: L.Routing.plan(waypoints, { createMarker: () => null })
}).addTo(map);
newRoutingControl.on('routesfound', (e) => {
const route = e.routes[0];
updateDirectionsData({
totalDistance: route.summary.totalDistance,
totalTime: route.summary.totalTime,
steps: route.instructions.map(i => ({ distance: i.distance, text: i.text }))
});
});
return newRoutingControl;
}, [map, routingControl, updateDirectionsData]);
const processVoiceCommand = useCallback(
async (transcription) => {
switch (transcription.command) {
case "zoom_in":
map.setZoom(map.getZoom() + 1);
break;
case "zoom_out":
map.setZoom(map.getZoom() - 1);
break;
case "search":
if (transcription.coords?.[0]) {
map.setView([transcription.coords[0].lat, transcription.coords[0].lng], 13);
}
break;
case "directions":
if (transcription.coords) {
const waypoints = transcription.coords.map(coord => L.latLng(coord.lat, coord.lng));
if (waypoints.length === 1 && currentLocation) {
waypoints.unshift(L.latLng(currentLocation[0], currentLocation[1]));
}
setRoutingControl(createCustomRoutingControl(waypoints));
}
break;
case "show_places":
setPlaceType(transcription.place_type);
break;
case "hide_places":
setPlaceType(null);
break;
case "clear_directions":
if (routingControl) {
routingControl.remove();
setRoutingControl(null);
updateDirectionsData(null);
}
break;
case "reset":
setPlaceType(null);
if (currentLocation) map.setView(currentLocation, 13);
break;
default:
console.log("Unknown command:", transcription.command);
}
},
[map, currentLocation, routingControl, createCustomRoutingControl, updateDirectionsData]
);
useEffect(() => {
setProcessVoiceCommand(() => processVoiceCommand);
}, [processVoiceCommand, setProcessVoiceCommand]);
return (
<>
{currentLocation && (
<Marker position={currentLocation}>
<Popup>📍 Your Location</Popup>
</Marker>
)}
<Places visible={placeType !== null} userLocation={currentLocation} placeType={placeType} />
</>
);
};
const MapView = ({ position, setProcessVoiceCommand, updateDirectionsData }) => {
return (
<div className="w-screen h-screen z-0">
<MapContainer center={position} zoom={13} className="absolute top-0 left-0 w-full h-full z-0" zoomControl={false}>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<MapController setProcessVoiceCommand={setProcessVoiceCommand} updateDirectionsData={updateDirectionsData} />
<ZoomControl position="bottomright" />
</MapContainer>
</div>
);
};
export default MapView;
import React, { useState, useCallback } from "react";
import opencage from "opencage-api-client";
import MapView from "./MapView";
import AudioRecorder from "./AudioRecorder";
import DirectionsSidebar from "./DirectionsSidebar";
const API_KEY = import.meta.env.VITE_GEOCODER_API_KEY;
const placeTypes = ["hospital", "restaurant", "pharmacy", "hotel", "atm"];
function SearchBar() {
const [query, setQuery] = useState("");
const [processVoiceCommandFn, setProcessVoiceCommandFn] = useState(null);
const [position, setPosition] = useState([20, 78]);
const [showDirections, setShowDirections] = useState(false);
const [directionsData, setDirectionsData] = useState(null);
const handleSearch = async (e) => {
e.preventDefault();
const placeType = placeTypes.find(type => query.toLowerCase() === type);
if (placeType) {
processVoiceCommandFn({ command: "show_places", place_type: placeType });
} else {
try {
const response = await opencage.geocode({ q: query, key: API_KEY });
if (response.results.length > 0) {
const { lat, lng } = response.results[0].geometry;
setPosition([lat, lng]);
processVoiceCommandFn({ command: "search", coords: [{ lat, lng }] });
} else {
console.log("No results found");
}
} catch (error) {
console.error("Error fetching geocode data:", error);
}
}
};
const handleVoiceCommand = useCallback((data) => {
if (processVoiceCommandFn) processVoiceCommandFn(data);
}, [processVoiceCommandFn]);
const updateDirectionsData = useCallback((data) => {
setDirectionsData(data);
setShowDirections(!!data);
}, []);
return (
<div className="relative w-screen h-screen">
<MapView position={position} setProcessVoiceCommand={setProcessVoiceCommandFn} updateDirectionsData={updateDirectionsData} />
{/* Search Bar */}
<div className="absolute top-4 left-4 bg-white p-3 rounded-lg shadow-md flex items-center w-full max-w-md z-50">
<form onSubmit={handleSearch} className="flex w-full items-center">
<input
type="text"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full bg-transparent outline-none text-gray-700 placeholder-gray-400 px-3"
/>
<button type="submit" className="text-gray-500 hover:text-gray-700 px-2">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
<path fillRule="evenodd" d="M10.5 3.75a6.75 6.75 0 1 0 0 13.5 6.75 6.75 0 0 0 0-13.5ZM2.25 10.5a8.25 8.25 0 1 1 14.59 5.28l4.69 4.69a.75.75 0 1 1-1.06 1.06l-4.69-4.69A8.25 8.25 0 0 1 2.25 10.5Z" clipRule="evenodd" />
</svg>
</button>
<AudioRecorder onTranscription={handleVoiceCommand} />
</form>
</div>
{/* Place Type Buttons (Separate from Search Bar) */}
<div className="absolute top-4 right-4 flex space-x-2 z-50">
{placeTypes.map(type => (
<button
key={type}
onClick={() => processVoiceCommandFn({ command: "show_places", place_type: type })}
className="bg-white p-2 rounded-lg shadow-md text-gray-700 hover:bg-gray-100 flex items-center"
>
{type === "hospital" && "🏥"}
{type === "restaurant" && "🍽️"}
{type === "pharmacy" && "💊"}
{type === "hotel" && "🏨"}
{type === "atm" && "💰"}
<span className="ml-2">{type.charAt(0).toUpperCase() + type.slice(1)}</span>
</button>
))}
<button
onClick={() => processVoiceCommandFn({ command: "hide_places" })}
className="bg-white p-2 rounded-lg shadow-md text-gray-700 hover:bg-gray-100 flex items-center"
>
❌ Hide Places
</button>
</div>
{showDirections && directionsData && (
<DirectionsSidebar directions={directionsData} onClose={() => setShowDirections(false)} onClear={() => processVoiceCommandFn({ command: "clear_directions" })} />
)}
</div>
);
}
export default SearchBar;
import React, { useState, useCallback } from "react";
import opencage from "opencage-api-client";
import MapView from "./MapView";
import AudioRecorder from "./AudioRecorder";
import DirectionsSidebar from "./DirectionsSidebar";
const API_KEY = import.meta.env.VITE_GEOCODER_API_KEY;
const placeTypes = ["hospital", "restaurant", "pharmacy", "hotel", "atm"];
function SearchBar() {
const [query, setQuery] = useState("");
const [processVoiceCommandFn, setProcessVoiceCommandFn] = useState(null);
const [position, setPosition] = useState([20, 78]);
const [showDirections, setShowDirections] = useState(false);
const [directionsData, setDirectionsData] = useState(null);
const handleSearch = async (e) => {
e.preventDefault();
const placeType = placeTypes.find(type => query.toLowerCase() === type);
if (placeType) {
processVoiceCommandFn({ command: "show_places", place_type: placeType });
} else {
try {
const response = await opencage.geocode({ q: query, key: API_KEY });
if (response.results.length > 0) {
const { lat, lng } = response.results[0].geometry;
setPosition([lat, lng]);
processVoiceCommandFn({ command: "search", coords: [{ lat, lng }] });
} else {
console.log("No results found");
}
} catch (error) {
console.error("Error fetching geocode data:", error);
}
}
};
const handleVoiceCommand = useCallback((data) => {
if (processVoiceCommandFn) processVoiceCommandFn(data);
}, [processVoiceCommandFn]);
const updateDirectionsData = useCallback((data) => {
setDirectionsData(data);
setShowDirections(!!data);
}, []);
return (
<div className="relative w-screen h-screen">
<MapView position={position} setProcessVoiceCommand={setProcessVoiceCommandFn} updateDirectionsData={updateDirectionsData} />
{/* Search Bar */}
<div className="absolute top-4 left-4 bg-white p-3 rounded-lg shadow-md flex items-center w-full max-w-md z-50">
<form onSubmit={handleSearch} className="flex w-full items-center">
<input
type="text"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full bg-transparent outline-none text-gray-700 placeholder-gray-400 px-3"
/>
<button type="submit" className="text-gray-500 hover:text-gray-700 px-2">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
<path fillRule="evenodd" d="M10.5 3.75a6.75 6.75 0 1 0 0 13.5 6.75 6.75 0 0 0 0-13.5ZM2.25 10.5a8.25 8.25 0 1 1 14.59 5.28l4.69 4.69a.75.75 0 1 1-1.06 1.06l-4.69-4.69A8.25 8.25 0 0 1 2.25 10.5Z" clipRule="evenodd" />
</svg>
</button>
<AudioRecorder onTranscription={handleVoiceCommand} />
</form>
</div>
{/* Place Type Buttons (Separate from Search Bar) */}
<div className="absolute top-4 right-4 flex space-x-2 z-50">
{placeTypes.map(type => (
<button
key={type}
onClick={() => processVoiceCommandFn({ command: "show_places", place_type: type })}
className="bg-white p-2 rounded-lg shadow-md text-gray-700 hover:bg-gray-100 flex items-center"
>
{type === "hospital" && "🏥"}
{type === "restaurant" && "🍽️"}
{type === "pharmacy" && "💊"}
{type === "hotel" && "🏨"}
{type === "atm" && "💰"}
<span className="ml-2">{type.charAt(0).toUpperCase() + type.slice(1)}</span>
</button>
))}
<button
onClick={() => processVoiceCommandFn({ command: "hide_places" })}
className="bg-white p-2 rounded-lg shadow-md text-gray-700 hover:bg-gray-100 flex items-center"
>
❌ Hide Places
</button>
</div>
{showDirections && directionsData && (
<DirectionsSidebar directions={directionsData} onClose={() => setShowDirections(false)} onClear={() => processVoiceCommandFn({ command: "clear_directions" })} />
)}
</div>
);
}
export default SearchBar;
import React from 'react';
function DirectionsSidebar({ directions, onClose, onClear }) {
if (!directions) return null;
// Format time from seconds to minutes and hours
const formatTime = (seconds) => {
if (seconds < 60) return `${seconds} sec`;
if (seconds < 3600) return `${Math.floor(seconds / 60)} min`;
const hours = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
return `${hours} hr ${mins} min`;
};
// Format distance from meters to km or miles
const formatDistance = (meters) => {
if (meters < 1000) return `${meters.toFixed(0)} m`;
return `${(meters / 1000).toFixed(1)} km`;
};
// Format total time and distance for the header
const totalTime = formatTime(directions.totalTime);
const totalDistance = formatDistance(directions.totalDistance);
return (
<div className="absolute top-16 right-4 w-80 max-h-screen-80 bg-white rounded-lg shadow-lg z-50 flex flex-col">
{/* Header */}
<div className="bg-blue-500 text-white p-4 rounded-t-lg flex justify-between items-center">
<div>
<h3 className="font-bold text-lg">Directions</h3>
<p className="text-sm">{totalDistance} • {totalTime}</p>
</div>
<div className="flex space-x-2">
{/* <button
onClick={onClear}
className="text-white hover:text-red-200"
title="Clear directions"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path
fillRule="evenodd"
d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z"
clipRule="evenodd"
/>
</svg>
</button> */}
<button
onClick={onClose}
className="text-white hover:text-gray-200"
title="Close sidebar"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-5 h-5"
>
<path
fillRule="evenodd"
d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zm-.53 14.03a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06L12 14.69 9.53 12.22a.75.75 0 00-1.06 1.06l3 3z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
</div>
{/* Directions List */}
<div className="overflow-y-auto p-2 max-h-96">
<ol className="list-none">
{directions.steps.map((step, index) => {
// Determine icon based on instruction type
let icon;
switch (step.type) {
case 'StartAt':
icon = '🚩';
break;
case 'WaypointReached':
icon = '📍';
break;
case 'DestinationReached':
icon = '🏁';
break;
case 'TurnRight':
icon = '↪️';
break;
case 'TurnLeft':
icon = '↩️';
break;
case 'TurnSlightRight':
icon = '⤴️';
break;
case 'TurnSlightLeft':
icon = '⤵️';
break;
case 'TurnSharpRight':
icon = '⤵️';
break;
case 'TurnSharpLeft':
icon = '⤴️';
break;
default:
icon = '➡️';
}
return (
<li key={index} className="py-3 border-b border-gray-100 flex items-start">
<div className="mr-3 mt-1">{icon}</div>
<div className="flex-1">
<p className="text-gray-800" dangerouslySetInnerHTML={{ __html: step.text }} />
<div className="text-xs text-gray-500 mt-1">
{formatDistance(step.distance)} • {formatTime(step.time)}
</div>
</div>
</li>
);
})}
</ol>
</div>
</div>
);
}
export default DirectionsSidebar;
import React, { useEffect, useState, useCallback, useRef } from "react";
import { MapContainer, TileLayer, Marker, Popup, useMap, ZoomControl } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import "leaflet-routing-machine";
// Define custom markers for different locations
const createCustomIcon = (iconUrl, className) => {
return L.icon({
iconUrl: iconUrl || "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png",
shadowSize: [41, 41],
className: className || ""
});
};
// Separate component to handle map operations
const MapController = ({ setProcessVoiceCommand, updateDirectionsData, position }) => {
const map = useMap();
const [routingControl, setRoutingControl] = useState(null);
const [currentLocation, setCurrentLocation] = useState(null);
const [fromMarker, setFromMarker] = useState(null);
const [toMarker, setToMarker] = useState(null);
// References to store markers
const fromMarkerRef = useRef(null);
const toMarkerRef = useRef(null);
// Add CSS to hide routing container completely
useEffect(() => {
const style = document.createElement("style");
style.textContent = `
.leaflet-routing-container, .leaflet-routing-alternatives-container {
display: none !important;
}
`;
document.head.appendChild(style);
return () => {
document.head.removeChild(style);
};
}, []);
useEffect(() => {
// Get user's location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setCurrentLocation([latitude, longitude]);
map.setView([latitude, longitude], 13);
},
(error) => console.error("Error getting location:", error)
);
}
}, [map]);
//Added to make the search function work
// Add a useEffect to watch for position changes
useEffect(() => {
if (position && position.length === 2) {
map.setView(position, 13);
}
}, [position, map]);
// Function to create and add markers
const addLocationMarkers = useCallback((fromCoords, toCoords) => {
// Remove existing markers
if (fromMarkerRef.current) {
map.removeLayer(fromMarkerRef.current);
}
if (toMarkerRef.current) {
map.removeLayer(toMarkerRef.current);
}
// Create custom icons
const fromIcon = createCustomIcon(null, "from-location-marker");
const toIcon = createCustomIcon(null, "to-location-marker");
// Create new markers
if (fromCoords) {
const newFromMarker = L.marker([fromCoords.lat, fromCoords.lng], { icon: fromIcon })
.addTo(map)
.bindPopup("📍 From Location");
fromMarkerRef.current = newFromMarker;
setFromMarker(newFromMarker);
}
if (toCoords) {
const newToMarker = L.marker([toCoords.lat, toCoords.lng], { icon: toIcon })
.addTo(map)
.bindPopup("🏁 Destination");
toMarkerRef.current = newToMarker;
setToMarker(newToMarker);
}
}, [map]);
// Custom routing control with events and UI customization
const createCustomRoutingControl = useCallback((waypoints) => {
// Remove existing routing control if it exists
if (routingControl) {
routingControl.remove();
}
// Add markers for from and to locations
if (waypoints.length >= 2) {
const fromCoords = { lat: waypoints[0].lat, lng: waypoints[0].lng };
const toCoords = { lat: waypoints[waypoints.length-1].lat, lng: waypoints[waypoints.length-1].lng };
addLocationMarkers(fromCoords, toCoords);
}
// Create a custom routing control with completely hidden UI
const newRoutingControl = L.Routing.control({
waypoints,
routeWhileDragging: true,
showAlternatives: true,
fitSelectedRoutes: true,
show: false,
lineOptions: {
styles: [{ color: '#3388ff', weight: 6 }],
extendToWaypoints: true,
missingRouteTolerance: 0
},
// Use a custom plan to avoid creating markers and UI elements
plan: L.Routing.plan(waypoints, {
createMarker: function() { return null; }, // No markers at waypoints
draggableWaypoints: false,
addWaypoints: false
}),
formatter: new L.Routing.Formatter({
units: 'metric'
})
});
// Add to map
newRoutingControl.addTo(map);
// Handle route finding errors
newRoutingControl.on('routingerror', function(e) {
console.error('Routing error:', e.error);
if (updateDirectionsData) {
updateDirectionsData({
error: true,
message: "Could not calculate route. Please try again later."
});
}
});
// Extract route info when available and send to parent component
newRoutingControl.on('routesfound', function(e) {
const routes = e.routes;
if (routes && routes.length > 0) {
const route = routes[0];
// Format directions data for sidebar
const formattedDirections = route.instructions.map(instruction => ({
distance: instruction.distance,
text: instruction.text,
time: instruction.time,
type: instruction.type
}));
const directionsData = {
totalDistance: route.summary.totalDistance,
totalTime: route.summary.totalTime,
steps: formattedDirections
};
// Update parent component with route data
if (updateDirectionsData) {
updateDirectionsData(directionsData);
}
}
});
// Make sure to hide any containers that might appear
setTimeout(() => {
const containers = document.querySelectorAll('.leaflet-routing-container');
containers.forEach(container => {
if (container) container.style.display = 'none';
});
}, 100);
return newRoutingControl;
}, [map, routingControl, updateDirectionsData]);
const processVoiceCommand = useCallback(
async (transcription) => {
if (!transcription?.command) {
console.warn("Invalid transcription:", transcription);
return;
}
console.log("Processing command:", transcription.command);
try {
switch (transcription.command) {
case "zoom_in":
if (transcription.coords?.[0]) {
map.setView(
[transcription.coords[0].lat, transcription.coords[0].lng],
map.getZoom()
);
}
else {
map.setZoom(map.getZoom() + 1);
}
break;
case "zoom_out":
map.setZoom(map.getZoom() - 1);
break;
case "search":
if (transcription.coords?.[0]) {
map.setView(
[transcription.coords[0].lat, transcription.coords[0].lng],
map.getZoom()
);
}
break;
case "directions":
if (transcription.coords) {
const waypoints = transcription.coords.map(coord =>
L.latLng(coord.lat, coord.lng)
);
if (waypoints.length === 1 && currentLocation) {
waypoints.unshift(L.latLng(currentLocation[0], currentLocation[1]));
}
const newRoutingControl = createCustomRoutingControl(waypoints);
setRoutingControl(newRoutingControl);
}
break;
case "clear_directions":
if (routingControl) {
routingControl.remove();
setRoutingControl(null);
// Also remove markers when clearing directions
if (fromMarkerRef.current) {
map.removeLayer(fromMarkerRef.current);
fromMarkerRef.current = null;
}
if (toMarkerRef.current) {
map.removeLayer(toMarkerRef.current);
toMarkerRef.current = null;
}
if (updateDirectionsData) {
updateDirectionsData(null);
}
}
break;
case "reset":
// Clear any markers and routing
if (routingControl) {
routingControl.remove();
setRoutingControl(null);
}
if (fromMarkerRef.current) {
map.removeLayer(fromMarkerRef.current);
fromMarkerRef.current = null;
}
if (toMarkerRef.current) {
map.removeLayer(toMarkerRef.current);
toMarkerRef.current = null;
}
if (currentLocation) {
map.setView(currentLocation, 13);
}
if (updateDirectionsData) {
updateDirectionsData(null);
}
break;
default:
console.log("Unknown command:", transcription.command);
}
} catch (error) {
console.error("Error processing voice command:", error);
}
},
[map, currentLocation, routingControl, createCustomRoutingControl, updateDirectionsData]
);
useEffect(() => {
setProcessVoiceCommand(() => processVoiceCommand);
}, [processVoiceCommand, setProcessVoiceCommand]);
return currentLocation ? (
<Marker position={currentLocation}>
<Popup>📍 Your Location</Popup>
</Marker>
) : null;
};
// Main MapView component
const MapView = ({ position, setProcessVoiceCommand, updateDirectionsData }) => {
// Use a ref for stable callback reference
const stableUpdateDirectionsData = useRef(updateDirectionsData);
// Update the ref when the prop changes
useEffect(() => {
stableUpdateDirectionsData.current = updateDirectionsData;
}, [updateDirectionsData]);
// Create a stable callback that uses the ref
const safeUpdateDirectionsData = useCallback((data) => {
if (stableUpdateDirectionsData.current) {
stableUpdateDirectionsData.current(data);
}
}, []);
return (
<div className="w-screen h-screen z-0">
<MapContainer
center={[20.5937, 78.9629]}
zoom={13}
className="absolute top-0 left-0 w-full h-full z-0"
zoomControl={false}
>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<MapController
setProcessVoiceCommand={setProcessVoiceCommand}
updateDirectionsData={safeUpdateDirectionsData}
position={position}
/>
<ZoomControl position="bottomright" />
</MapContainer>
</div>
);
};
export default MapView;
import React, { useState, useCallback, useEffect, useRef } from "react";
import opencage from "opencage-api-client";
import MapView from "./MapView";
import AudioRecorder from "./AudioRecorder";
import DirectionsSidebar from "./DirectionsSidebar";
import DirectionsInputSidebar from "./DirectionsInputSidebar";
const API_KEY = import.meta.env.VITE_GEOCODER_API_KEY;
function SearchBar() {
const [query, setQuery] = useState("");
const [processVoiceCommandFn, setProcessVoiceCommandFn] = useState(null);
const [position, setPosition] = useState([20, 78]); // Default: India (lat, lng)
const [showDirections, setShowDirections] = useState(false);
const [directionsData, setDirectionsData] = useState(null);
const [suggestions, setSuggestions] = useState([]);
const [showSuggestions, setShowSuggestions] = useState(false);
const searchRef = useRef(null);
const [currentLocation, setCurrentLocation] = useState(null);
const [showDirectionsInput, setShowDirectionsInput] = useState(false);
// Get user's current location on component mount
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setCurrentLocation([latitude, longitude]);
},
(error) => console.error("Error getting location:", error)
);
}
}, []);
// Handle outside clicks to close suggestions
useEffect(() => {
function handleClickOutside(event) {
if (searchRef.current && !searchRef.current.contains(event.target)) {
setSuggestions([]);
setShowSuggestions(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
// Fetch suggestions when query changes
useEffect(() => {
const fetchSuggestions = async () => {
if (query.length < 3) {
setSuggestions([]);
return;
}
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5`,
{
headers: {
"Accept-Language": "en-US,en;q=0.9",
"User-Agent": "SDS"
}
}
);
if (response.ok) {
const data = await response.json();
setSuggestions(data);
setShowSuggestions(data.length > 0);
}
} catch (error) {
console.error("Error fetching suggestions:", error);
}
};
// Debounce the search to avoid too many requests
const timeoutId = setTimeout(() => {
if (query.length >= 3) {
fetchSuggestions();
}
}, 300);