0

I'm trying to clear the route when I add a new waypoint. Only two waypoints should should show. However, when adding an additional waypoint, Leaflet will show the old route instead of clearing it. I checked the console logs and it definitely only shows two waypoints, and the first one is "spliced" out and replace with a new waypoint. Any ideas on how to reset the map?

import { useEffect, useRef } from 'react';
import Leaflet from 'leaflet';
import * as ReactLeaflet from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import "leaflet-routing-machine"
import { useMapStore } from '@/store/mapStore'

const { MapContainer, FeatureGroup, GeoJSON, useMap } = ReactLeaflet;

function MyComponent() {
  const map = useMap()
  const lat = useMapStore(state => state.lat)
  const lng = useMapStore(state => state.lng)

  // https://www.npmjs.com/package/leaflet-routing-machine/v/0.2.0

  useEffect(() => {
    Leaflet.Icon.Default.mergeOptions({
      iconRetinaUrl: 'images/marker-icon-2x.png',
      iconUrl: 'images/marker-icon.png',
      shadowUrl: 'images/marker-shadow.png'
    });

    let routeControl = Leaflet.Routing.control({
      waypoints: [
        Leaflet.latLng(-35.3080, 149.1250),
        Leaflet.latLng(-35.3080, 149.1250)
      ],
      router: Leaflet.Routing.mapbox(process.env.NEXT_PUBLIC_MAPBOX_KEY)
      // your other options go here
    }).addTo(map);

    if (lat) {
      routeControl.spliceWaypoints(0, 1, Leaflet.latLng(-35.3080, 149.1250))

      const latlng = Leaflet.latLng(lat, lng)

      routeControl.spliceWaypoints(0, 1, latlng)
      routeControl.route()
    }

    routeControl.getWaypoints().forEach((waypoint, index) => {
      console.log(waypoint)
    })

  }, [map, lat, lng])
  return null
}

const Map = ({ children, className, width, height, ...rest }) => {
  return (
    <MapContainer
      {...rest}>
      <MyComponent />
      {children(ReactLeaflet, Leaflet)}
    </MapContainer>
  )
}

export default Map;

Screenshots below: Adding the first route

Adding a new second waypoint leaves the old route in the map

Checked the API docs here: https://www.liedman.net/leaflet-routing-machine/api/

0