Leaflet map not showing properly in bootstrap 3.0 modal

本秂侑毒 提交于 2019-11-27 08:55:27

I think what is happening is that, when the map is created, the container width/height for your `map-canvas' element has not yet been adjusted to the width/height of the modal dialog. This causes the map size to be incorrect (smaller) than what it should be.

You can fix this by calling map.invalidateSize(). This will work to re-adjust the width/height bounds of the L.Map's container.

You can automatically call this by hooking into the event where the Bootstrap modal becomes shown.

$('#myModal').on('show.bs.modal', function(){
  setTimeout(function() {
    map.invalidateSize();
  }, 10);
 });

Insert this code into your JavaScript. When the modal is shown, the map will then invalidate its size. The timeout is because there may be some animation/transition time for the modal to display and be added to the DOM.

You should probably avoid using setTimeout with a randomly chosen delay. A better way using the 'shown.bs.modal' event instead of 'show.bs.modal':

modal.on('shown.bs.modal', function(){
    setTimeout(function() {
        map.invalidateSize();
   }, 1);
})

Or use underscore's defer :

modal.on('shown.bs.modal', function(){
    _.defer(map.invalidateSize.bind(map));
})

I use this workaround:

.modal {
  visibility: hidden;
  display: block;
}

.modal[aria-hidden='false'] {
  visibility: visible;
  display: block;
}

This worked for me -

 $('#gmap').on('shown.bs.tab', function (e) {
    //call the clear map event first
    clearMap();
    //resize the map - this is the important part for you
   map.invalidateSize(true);
   //load the map once all layers cleared
   loadMap();
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!