9

I am dynamically adding a leaflet map to a div. The map is only shown partially, see picture. Once I resize the browser window the map is completely shown. Is there a way around this? I tried some initial ideas, see // in code. But none of them worked.incomplete map

    function mapThis(lat,long,wikiTitle){       

     var div_Id= "#wikiExtract"+wikiTitle
     var map_Id= "map"+wikiTitle
     $(div_Id).append("<div id='"+map_Id+"' style='width: 600px; height:
     400px'></div>"); 
     var map = L.map(map_Id).setView([lat, long], 10);

     L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
     maxZoom: 18,
     attribution: 'Map data &copy; <a
     href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-
          SA</a>'
      }).addTo(map);


     //$("#"+map_Id).css( "height", "500px" );
     //map.invalidateSize()
     //$("#"+map_Id).hide()   
     //$("#"+map_Id).show()
     //$(window).trigger('resize');

    }
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
user2133375
  • 119
  • 1
  • 2
  • 7

3 Answers3

15

you can use this code : it work find for me.

setInterval(function () {
   map.invalidateSize();
}, 100);
fbarikzehy
  • 4,885
  • 2
  • 33
  • 39
HamidReza
  • 1,726
  • 20
  • 15
12

If at least you have the map working (except for the incompleteness of tiles loading), you could simply call map.invalidateSize() once your map's div container is revealed / inserted into DOM with final size.

Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • I tried this, but it didn't lead to a changed behaviour. – user2133375 Mar 16 '16 at 18:09
  • Make sure you call it **after** your map container is revealed and has its final dimensions. It is called automatically when you do a browser window resize for example, but of course you do not want to wait for your user to do that operation just to get your map working. – ghybs Mar 17 '16 at 01:36
  • Thank you. I changed my usecase accordingly. – user2133375 Mar 17 '16 at 19:03
  • I can not call `map.invalidateSize()` after map container is revealed. I get reference is not defined. How to get `map` variable to work with? – Sashko Lykhenko Sep 26 '18 at 19:31
  • 1
    Hi @SashkoLykhenko, sounds like you should better open your own question with details of your issue, including some sample code to reproduce the problem. Otherwise it is impossible to tell how to help you with so few details. – ghybs Sep 27 '18 at 00:47
2

If using JQuery, the following code updates the size once the document is ready:

$(document).ready(function () {
    mymap.invalidateSize();
});
Daniel H
  • 51
  • 1
  • 5