Dhruv Kundu
Dhruv Kundu

Reputation: 1

(React JS) leaflet-routing-machine icon rotation

"The issue I have been facing is that I'm unable to rotate the icon marker in my project to the desired direction. For example, if I start from the start point and move towards the end point, there are many turns in the path. I want my icon to align itself with the path direction: if there's a left turn, the icon should face left; if there's a right turn, it should face right; and if there's a U-turn in the road, the icon should reflect that as well."

THIS IS THE CODE

    locateUser();

    map.on('locationfound', (e) => {
      const userLocation = [e.latlng.lat, e.latlng.lng];
      if (!markerRef.current) {
        const marker = L.marker(userLocation).addTo(map);
        markerRef.current = marker;
      } else {
        markerRef.current.setLatLng(userLocation);
      }
    });

    map.on('locationerror', (e) => {
      console.error('Error locating user:', e.message);
    });

    map.on('click', function (e) {
      L.marker([e.latlng.lat, e.latlng.lng]).addTo(map);
      L.Routing.control({
        waypoints: [
          L.latLng(markerRef.current.getLatLng()),
          L.latLng(e.latlng.lat, e.latlng.lng),
        ],
        lineOptions: {
          styles: [
            {
              color: 'blue',
              weight: 4,
              opacity: 0.7,
            },
          ],
        },
        routeWhileDragging: false,
        geocoder: L.Control.Geocoder.nominatim(),
        addWaypoints: false,
        draggableWaypoints: false,
        fitSelectedRoutes: true,
        showAlternatives: true,
      })
        .on('routesfound', function (e) {
          const route = e.routes[0];
          route.coordinates.forEach((c, i) => {
            setTimeout(() => {
              markerRef.current.setLatLng([c.lat, c.lng]);

              if (i < route.coordinates.length - 1) {
                const p1 = route.coordinates[i];
                const p2 = route.coordinates[i + 1];
                const angle = calculateAngle(p1, p2);

                console.log('Rotation Angle:', angle);

                const rotatedIcon = L.icon({
                  iconUrl: '/car.png',
                  iconSize: [38, 38],
                  iconAnchor: [19, 19],
                  rotationAngle: angle
                });
                markerRef.current.setIcon(rotatedIcon);
              }
            }, 100 * i);
          });
        })
        .addTo(map);
    });
  }, [map]);

Upvotes: 0

Views: 116

Answers (0)

Related Questions