Change Tile At TileLayer At State Change
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.
function TileLayer({ 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);
return null;
}
import it as a child of MapContainer
<MapContainer center={center} zoom={zoom} style={{ height: "100vh" }}>
<ChangeView center={center} zoom={zoom} />
<TileLayer darkMode={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);
<>
<button onClick={() => setIsDark((prevState) => !prevState)}>
Change basemap
</button>
<TrackerMap center={position} zoom={12} darkMode={isDark} />
</>
Post a Comment for "Change Tile At TileLayer At State Change"