this is react code im using leaflet library and its routing machine im lost in this trying to switch osrm server error is uploaded as image
import {
MapContainer,
Marker,
Popup,
TileLayer,
useMap,
useMapEvents,
} from "react-leaflet";
import { Link, useNavigate, useParams } from "react-router-dom";
import L from "leaflet";
import "leaflet-routing-machine";
function Map() {
const { id } = useParams();
const navigate = useNavigate();
const [markers, setMarkers] = useState([]);
const [marker, setMarker] = useState([51, 0]);
const [myPosition, setMyPosition] = useState([51, 0]);
const triangleIcon = new L.Icon({
iconUrl: "../../public/icons8-triangle-48.png",
iconSize: [20, 20],
});
useEffect(() => {
// navigator.geolocation.watchPosition((position) => {
// setMyPosition([position.coords.latitude, position.coords.longitude]);
// });
const geoWatch = navigator.geolocation.watchPosition(
(position) => {
setMyPosition([position.coords.latitude, position.coords.longitude]);
},
(error) => {
console.error("Error getting current position:", error);
},
);
return () => navigator.geolocation.clearWatch(geoWatch);
}, []);
console.log(myPosition);
function AddMarkerToClick() {
const map = useMap();
useMapEvents({
click(e) {
const clickedPosition = [e.latlng.lat, e.latlng.lng];
navigate(`/map/${id}/?lat=${e.latlng.lat}&lng=${e.latlng.lng}`);
setMarker(clickedPosition);
const newMarker = {
id: markers.length + 1,
position: e.latlng,
};
setMarkers((prevMarkers) => [...prevMarkers, newMarker]);
// Remove previous routes
if (map.routeControl) {
map.removeControl(map.routeControl);
}
// Create a new route from current position to clicked position
// const routeControl = L.Routing.control({
// waypoints: [
// L.latLng(myPosition[0], myPosition[1]),
// L.latLng(clickedPosition[0], clickedPosition[1]),
// ],
// routeWhileDragging: true,
// createMarker: function () {
// return null;
// }, // Remove default markers
// }).addTo(map);
// const routeControl = L.Routing.control({
// waypoints: routeCoordinates.map((coord) =>
// L.latLng(coord.lat, coord.lng),
// ),
// routeWhileDragging: true,
// createMarker: function () {
// return null;
// }, // Remove default markers
// router: L.Routing.osrmv1({
// serviceUrl:
// "https://api.openrouteservice.org/v2/directions/driving-car",
// }),
// }).addTo(map);
// map.routeControl = routeControl; // Store route control for later use
// // Remove previous routes
// if (map.routeControl) {
// map.removeControl(map.routeControl);
// }
// Function to fetch route from OpenRouteService
const fetchRoute = async (start, end) => {
const apiKey =
"api-key";
const url = `https://api.openrouteservice.org/v2/directions/driving-car?api_key=${apiKey}&start=${start.lng},${start.lat}&end=${end.lng},${end.lat}`;
const payload = {
coordinates: [
[start.lng, start.lat],
[end.lng, end.lat],
],
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
console.log(data);
console.log(
data.metadata.query.coordinates.map((coord) =>
console.log(coord.lat),
),
"reeeeeeeeeeeeeeeeeee",
);
const routeCoordinates = data.metadata.query.coordinates.map(
(coord) => L.latLng(coord[1], coord[0]),
);
return routeCoordinates;
};
// Create a new route from current position to clicked position
const createRoute = async () => {
try {
const routeCoordinates = await fetchRoute(
L.latLng(myPosition[0], myPosition[1]),
L.latLng(clickedPosition[0], clickedPosition[1]),
);
console.log(routeCoordinates);
const routeControl = L.Routing.control({
waypoints: routeCoordinates.map((coord) =>
L.latLng(coord.lat, coord.lng),
),
routeWhileDragging: true,
createMarker: function () {
return null;
}, // Remove default markers
router: L.Routing.osrmv1({
serviceUrl:
"https://api.openrouteservice.org/v2/directions/driving-car",
}),
}).addTo(map);
// map.routeControl = routeControl; // Store route control for later use
} catch (error) {
console.error("Error fetching route:", error);
}
};
createRoute();
},
});
return null;
}
function UpdateMapCenter({ position }) {
const map = useMap();
useEffect(() => {
if (position) {
map.panTo(position);
}
}, [position, map]);
return null;
}
return (
// <Link to={`/map/${id}/?lat=${marker[0]}`}>
<MapContainer
// key={myPosition}
center={myPosition}
zoom={17}
scrollWheelZoom={true}
className="h-screen"
>
<UpdateMapCenter position={myPosition} />
<AddMarkerToClick />
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png"
/>
<Marker position={marker}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
<Marker position={myPosition} icon={triangleIcon}></Marker>
</MapContainer>
// </Link>
);
}
export default Map;