Problems with leaflet.js

I have used leaflet.js a few times without problems but have a site where when the page is loaded initially the leaflet map does not show. When I resize the window, it shows fine again. This occurs no matter the initial size.

I have added the stylesheet link…

         <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
   integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
   crossorigin=""/>

And added the div for the map…

  <div id="mapid"></div>

Then at the bottom of the page added this code…

<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
       integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
       crossorigin=""></script>  
    <script>
             
        var mymap = L.map('mapid').setView([55.70926, -3.87980], 10);
        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>,          
Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets',
        accessToken: 'My access token was added here.'
        }).addTo(mymap);
      	L.polygon([
        [55.88084,-4.33693],
        [55.86716,-3.89044],
        [55.70384,-3.73715],
        [55.66049,-3.82521],
        [55.64809,-4.14605]
        ]).addTo(mymap);
 </script>

Can anyone advise how I get around this problem please?

After 2 days of trying to get a solution to this and trying all the workarounds and hacks online, I’ve finally got it working.
I simple added this, hope it helps someone else. …

  $(window).trigger('resize');  
1 Like

Hi @Hlforr, there would certainly be a proper solution other than this workaround… just a shot in the dark, but did you maybe forget to set an initial height for the map (that would later be set with JS on resize)? Other than that, your code works fine for me…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.