Skip to content Skip to sidebar Skip to footer

Change Tile At Tilelayer At State Change

My question is how to change url of tile map in that case: function ChangeView({ center, zoom }) { const map = useMap(); map.setView(center, zoom); return null; } f

Solution 1:

According to the official docs

Child components in React Leaflet use their props as options when creating the corresponding Leaflet instance, as described in Leaflet's documentation.

By default these props should be treated as immutable, only the props explicitely documented as mutable in this page will affect the Leaflet element when changed.

Therefore you will need an extra component which will toggle the map basemap tilelayer using map.addLayer() and you will not need to use react-leaflet's TileLayer but you will build your own. You can further adjust it to your requirements.

functionTileLayer({ darkMode }) {
  const map = useMap();
  var dark = L.tileLayer(
    "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png"
  );
  const normal = L.tileLayer(
    "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
  );
  map.addLayer(darkMode ? dark : normal);

  returnnull;
}

import it as a child of MapContainer

<MapContainercenter={center}zoom={zoom}style={{height: "100vh" }}><ChangeViewcenter={center}zoom={zoom} /><TileLayerdarkMode={darkMode} /></MapContainer>

Now on the component where you use TrackerMap create a state variable to hold the darkMode status and use for instance a button to toggle the darkMode status.

const [isDark, setIsDark] = useState(false);

<><buttononClick={() => setIsDark((prevState) => !prevState)}>
        Change basemap
  </button><TrackerMapcenter={position}zoom={12}darkMode={isDark} /></>

Demo

Post a Comment for "Change Tile At Tilelayer At State Change"