Reactjs =>leaflet-routing-machine waypoint render 2 times

265 Views Asked by At

here I get a bug when trying the leaflet-routing-machine lib.

The bug is that the "Waypoints" section renders 2 times.

why is it able to render 2 times? Can you guys help me? Thank you

enter image description here

My Code in below =>

1

There are 1 best solutions below

0
Kia Kalista On

My Code =

import { useEffect } from "react";
import L from "leaflet";
import "leaflet-routing-machine/dist/leaflet-routing-machine.css";
import "leaflet-routing-machine";
import { useMap } from "react-leaflet";

L.Marker.prototype.options.icon = L.icon({
  iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
});

export default function Routing() {
  const map = useMap();

  const routingControl = L.Routing.control({
    waypoints: [
      L.latLng(-6.3094117, 106.8240261),
      L.latLng(-6.2185648, 106.7996082),
    ],
    lineOptions: {
      styles: [{ color: "#6FA1EC", weight: 4 }],
    },
    routeWhileDragging: true,
    draggableWaypoints: true,
    fitSelectedRoutes: true,
  }).addTo(map);

  useEffect(() => {
    return () => map.removeControl(routingControl);
  }, [map, routingControl]);

  function createButton(label, container) {
    let btn = L.DomUtil.create("button", "", container);
    btn.setAttribute("type", "button");
    btn.innerHTML = label;
    return btn;
  }
  map.on("click", function (e) {
    let container = L.DomUtil.create("div"),
      startBtn = createButton("Start from this location", container),
      destBtn = createButton("Go to this location", container);
    container.setAttribute("class", "leaflet-popup-btn-box");

    L.DomEvent.on(startBtn, "click", function () {
      routingControl.spliceWaypoints(0, 1, e.latlng);
      map.closePopup();
    });
    L.DomEvent.on(destBtn, "click", function () {
      routingControl.spliceWaypoints(
        routingControl.getWaypoints().length - 1,
        1,
        e.latlng
      );
      map.closePopup();
    });

    L.popup().setContent(container).setLatLng(e.latlng).openOn(map);
  });

  return null;
}