Home > Software design >  How do I hide and show a leaflet map if I'm using checkboxes to display different items?
How do I hide and show a leaflet map if I'm using checkboxes to display different items?

Time:01-03

<body>
    <script>
        function mapin() {
            var map1 = L.map('map').setView([0,0],1);
            L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=RM234QFDXeTVS0G8RUEl',
            {attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy;
MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>',}).addTo(map1);
            var markar = L.marker([51.5, -0.09]).addTo(map1);
        }
        function myFunction() {
            if(vehicle1.checked == 1){
                document.getElementById("map").style.display="block";
                mapin();
            }
            else{
                document.getElementById("map").innerHTML = ""
                
            }     
            if(vehicle2.checked == 1){
                document.getElementById("map2").innerHTML = "Option 2 checked"
            }
            else{
                document.getElementById("map2").innerHTML = ""
            }  
            if(vehicle3.checked == 1){
                document.getElementById("text3").innerHTML = "Option 3 checked"
            }
            else{
                document.getElementById("text3").innerHTML = ""
            }  
        }
    </script>
    <div >

        <div id="map"></div>
        <div id="map2"></div>
        <div><p id="text3"></p></div>
    </div>
    <div >
        <div >This is top<br>
            <input type="checkbox" id="vehicle1" name="option1" value="1" onclick="myFunction()">
            <label for="vehicle1"> this is option 1</label><br>
            <input type="checkbox" id="vehicle2" name="option2" value="2" onclick="myFunction()">
            <label for="vehicle2"> this is option 2</label><br>
            <input type="checkbox" id="vehicle3" name="option3" value="3" onclick="myFunction()">
            <label for="vehicle3"> this is option 3</label><br>
        </div>
    </div>
</body>

Here I am displaying/hiding different text using different checkboxes. If I want to do the same thing for maps how will I do so? Hiding and showing different maps on checking and unchecking different checkboxes.

CodePudding user response:

You can instantiate as many maps as you like, even if they are currently hidden with style.display = "none". But make sure to call the invalidateSize() method once they are revealed.

Avoid "hiding" them by flushing the map container innerHTML. You would have to re-instantiate the map every time you reveal it. Just changing the display style to "none" should be enough.

  • Related