Getting CORS error

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='&copy; <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;

help??? hmmm

Hi, remember this is free community support :wink:

Please try out our JavaScript package: openrouteservice-js - npm

As a side note, you are mixing up GET and POST requests. If you use POST, you don’t need to add the start and end to the URL any more.

i dont know what you mean by free community support? support is still support isnt it?
i do need GET request to get route data dont i?
so yea i tried your package im confused i dont know what im doing wrong i would be thankful if you chek this out and just ignore commented out code

import {
  MapContainer,
  Marker,
  Polyline,
  Popup,
  TileLayer,
  useMap,
  useMapEvents,
} from "react-leaflet";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import L from "leaflet";
import "leaflet-routing-machine";
import { useDispatch, useSelector } from "react-redux";
import { openSideBarForm } from "../redux/mainPageSlice";
import useUpdateMapPerSec from "../hooks/useUpdateMapPerSec";
import Openrouteservice from "openrouteservice-js";
function Map() {
  const dispatch = useDispatch();
  const { sideBarFormOpen, routeLocked } = useSelector(
    (store) => store.mainPage,
  );

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const lat = searchParams?.get("lat");
  const lng = searchParams?.get("lng");

  const { id } = useParams();
  const navigate = useNavigate();
  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],
  });

  const mapRef = useRef(null);
  const [route, setRoute] = useState([]); // State to track the route

  useEffect(() => {
    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);
  }, []);

  // useEffect(() => {
  //   async function ors() {
  //     // Add your api_key here
  //     let orsDirections = new Openrouteservice.Directions({
  //       api_key: "API_KEY",
  //     });

  //     try {
  //       let response = await orsDirections.calculate({
  //         coordinates: [
  //           [8.690958, 49.404662],
  //           [8.687868, 49.390139],
  //         ],
  //         profile: "driving-car",
  //         // restrictions: {
  //         //   height: 10,
  //         //   weight: 5,
  //         // },
  //         // extra_info: ["waytype", "steepness"],
  //         // avoidables: ["highways", "tollways", "ferries", "fords"],
  //         // avoid_polygons: {
  //         //   type: "Polygon",
  //         //   coordinates: [
  //         //     [
  //         //       [8.683533668518066, 49.41987949639816],
  //         //       [8.680272102355957, 49.41812070066643],
  //         //       [8.683919906616211, 49.4132348262363],
  //         //       [8.689756393432617, 49.41806486484901],
  //         //       [8.683533668518066, 49.41987949639816],
  //         //     ],
  //         //   ],
  //         // },
  //         format: "json",
  //       });
  //       // Add your own result handling here
  //       console.log("response: ", response);
  //     } catch (err) {
  //       console.log("An error occurred: " + err.status);
  //       console.error(await err.response.json());
  //     }
  //   }
  //   ors();
  // }, []);

  // const updateRoute = useCallback(() => {
  //   const map = mapRef.current;
  //   if (map.routeControl) {
  //     map.removeControl(map.routeControl);
  //   }

  //   const routeControl = L.Routing.control({
  //     waypoints: [L.latLng(myPosition[0], myPosition[1]), L.latLng(lat, lng)],
  //     routeWhileDragging: true,
  //     createMarker: function () {
  //       return null;
  //     },
  //   }).addTo(map);

  //   map.routeControl = routeControl;
  // }, [lat, lng, myPosition]);

  const updateRoute = useCallback(async () => {
    if (routeLocked) return;
    if (!lat || !lng) return;

    let orsDirections = new Openrouteservice.Directions({
      api_key: "API_KEY", // Replace with your Openrouteservice API key
    });
    console.log(orsDirections);
    try {
      let response = await orsDirections.calculate({
        coordinates: [
          [myPosition[1], myPosition[0]], // [lng, lat]
          [lat, lng], // [lng, lat]
        ],
        profile: "driving-car",
        format: "json",
      });
      console.log(response);

      const coordinates = response.routes[0].geometry.coordinates.map(
        (coord) => [coord[1], coord[0]],
      );
      // console.log(coordinates);
      setRoute(coordinates);
    } catch (err) {
      // console.log("An error occurred: " + err.status);
      // console.error(await err.response.json());
    }
  }, [myPosition, lat, lng, routeLocked]);

  function AddMarkerToClick() {
    const mapp = useMap();
    mapRef.current = mapp;
    // const map = mapRef.current;
    useMapEvents({
      click(e) {
        const clickedPosition = [e.latlng.lat, e.latlng.lng];
        navigate(`/map/${id}/?lat=${e.latlng.lat}&lng=${e.latlng.lng}`);
        setMarker(clickedPosition);
        dispatch(openSideBarForm()); //pozicia da poziciis tipi

        // // 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);

        // map.routeControl = routeControl;
        updateRoute();
      },
    });

    return null;
  }

  function UpdateMapCenter({ position }) {
    const map = useMap();
    useEffect(() => {
      if (position) {
        map.panTo(position);
      }
    }, [position, map]);
    return null;
  }

  useEffect(() => {
    // console.log(myPosition);
    if (routeLocked) return;
    if (!mapRef.current) return;
    if (!lat || !lng) return;

    const intervalId = setInterval(() => {
      updateRoute();
    }, 1_000);

    return () => clearInterval(intervalId);
  }, [routeLocked, myPosition, lat, lng, updateRoute]);

  return (
    <MapContainer
      center={myPosition}
      zoom={17}
      scrollWheelZoom={true}
      className="h-screen"
    >
      <UpdateMapCenter position={myPosition} />
      <AddMarkerToClick />
      <TileLayer
        attribution='&copy; <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>Destination</Popup>
      </Marker>

      <Marker position={myPosition} icon={triangleIcon}></Marker>

      {route.length > 0 && <Polyline positions={route} color="blue" />}
    </MapContainer>
  );
}

export default Map;

this is error

open route service is as painfull as nail in foot, if somone is reading this dont use open route service. even their own moderators dont know solution.

graphopper literly better option in any ways 15 k requests daily on each key and you can create lot of keys screw you open route service :slight_smile:

Hey,

I’m sorry that the answers to your question made you feel that way. What is meant by

is that this is a community support forum, not a paid support line. As such, you can not expect an answer within a defined amount of time.
Of course we still have an interest to help everybody with their issues, but from time to time it might take a bit longer until we get back to you.

When posting on here, you are asked to describe your problem precisely, including full requests and responses.

What you gave was a huge amount of javascript code using third-party frameworks and libraries. Remember, this is not a javascript support forum, but an openrouteservice support forum. We can help you best if what you are doing isn’t obscured, but rather raw requests.

I believe that the issue in your case was caused by a recent change to our infrastructure, causing problems, compare this thread that reports a similar problem.
These problems have been addressed by now, so your request might work.

If not, please post a minimal example of a non-working request. A cURL request or a single request to our official client would be fantastic.

On a different note, please refrain from using profane language in a public forum and state your opinion civilized.

Best regards

3 Likes