I have two buttons and the idea is: when I click a button, it changes the basemap state. However, each time I click on the button to change the basemap tilelayer, I get
Error: Map container is already initialized.
Does anyone know of a way to fix this? My code is below.
useEffect(() => {
console.log('Initializing map');
var map = L.map(ref.current).setView([53.9, -9.5], 10);
setLeafletMap(map);
const osm = L.tileLayer(
'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',
{
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 20,
}
);
const aerial = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{
attribution:'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}
);
const basemapLayers = {
'OSM': osm,
'Aerial': aerial
};
basemapLayers[selectedBasemap].addTo(map);
}, [selectedBasemap]);