React Leaflet => Sidebar render twice

158 Views Asked by At

here I got a bug that from yesterday until now got the solution.

So the bug is that the sidebar appears 2 times as shown in the picture. enter image description here

What do you think the solution is?

Thank you, I really appreciate your help.

My Code https://pastebin.com/xZaKFLaS

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: "#ED2A2A", weight: 4 }],
    },
    routeWhileDragging: true,
    draggableWaypoints: true,
    fitSelectedRoutes: true,
  }).addTo(map);

  useEffect(() => {
    return routingControl.getPlan();
  }, [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);

    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;
}
1

There are 1 best solutions below

2
Nir Alfasi On

Seems like it's a known bug/limitation and there are workarounds.

The simplest, I think, is to not provide waypoints (and allow the users to create their own. The following code works for me:

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

enter image description here