0

according to this codesandbox I was trying to change the left or right layer of my map by mutating the state but it change the whole map tile when I'm changing it. Any idea suggestion would be greatly appreciated.

Emad Baqeri
  • 2,333
  • 2
  • 14
  • 29

1 Answers1

1

Your code is unreasonably complex in my opinion so I will provide a simple example and you can adjust it to your code.

You need to do only two steps to achieve your goal.

  1. Store leaflet-side-by-side instance when the page lands.
  2. use it to call setLeftLayers which works fine by the way

On useEffect you implement step 1. On the event handler you implement step 2.

function App() {
  const position = [51.505, -0.09];
  const [map, setMap] = useState(null);
  const [sideBySide, setSidebySide] = useState(null);

  useEffect(() => {
    if (!map) return;

    var osmLayer = L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
      attribution:
        '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    var stamenLayer = L.tileLayer(
      "https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.png",
      {
        attribution:
          'Map tiles by <a href="http://stamen.com">Stamen Design</a>, ' +
          '<a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; ' +
          "Map data {attribution.OpenStreetMap}",
        minZoom: 1,
        maxZoom: 16
      }
    ).addTo(map);

    const sideBySide = L.control.sideBySide(stamenLayer, osmLayer).addTo(map);
    setSidebySide(sideBySide);
  }, [map]);

  const handleClick = () => {
    sideBySide.setLeftLayers(
      L.tileLayer("https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png", {
        attribution:
          '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map)
    );
  };

  return (
    <>
      <MapContainer
        center={position}
        zoom={13}
        style={{ height: "90vh" }}
        whenCreated={setMap}
      ></MapContainer>
      <button onClick={handleClick}>Change left tiles</button>
    </>
  );
}

Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
  • If sideByside Control has already been added to the map then why sideBySide.setLeftLayers() need to be added again to map through .addTo(map); – u tyagi Jul 06 '23 at 06:38