Why are you adding new map? You probably have it already in global variable map
, which is initialized on load. Work with this and change only layers on change/click. Something like this:
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
var geojsonLayers = {
'states': L.geoJson(statesData),
'statesTwo': L.geoJson(statesDataTwo)
};
function change()
{
if (document.querySelector('.onoffswitch-checkbox').checked) {
map.addLayer(geojsonLayers.states);
if (map.hasLayer(geojsonLayers.statesTwo)) {
map.removeLayer(geojsonLayers.statesTwo);
}
} else {
map.addLayer(geojsonLayers.statesTwo);
if (map.hasLayer(geojsonLayers.states)) {
map.removeLayer(geojsonLayers.states);
}
}
}