I have a map in leaflet,using the following code,when the page load, the map doesn't completely been shown,i don't know why, how can this be solved?
var Mmap = L.map('Modalmap').setView([8.7144, 125.7481],8);
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright"></a>',
subdomains: ['a','b','c']
}).addTo(Mmap);
L.control.scale({imperial:false}).addTo(Mmap);
var north = L.control({position: "topleft"});
north.onAdd = function(map) {
var div = L.DomUtil.create("div", "info_legend leaflet-bar");
div.innerHTML = '<img src="../lib/css/images/north-arrow-2.png" width="100%" height="100%">';
return div;
}
north.addTo(Mmap);
var geocoder = L.Control.geocoder({
defaultMarkGeocode: false
})
.on('markgeocode', function(e) {
var box = e.geocode.center;
document.getElementById("Latitude").value = box.lat;
document.getElementById("Longitude").value = box.lng;
var MarkLayer=L.marker([box.lat,box.lng]).addTo(Mmap);
var group = new L.featureGroup([MarkLayer]);
Mmap.fitBounds(group.getBounds());
}).addTo(Mmap);
This map is in a modal which i am calling it Modal-1
from a navbar
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav" style="margin-top: -3px;">
<li class="dropdown"><a href="#" data-toggle="modal" data-target="#modal-1">New Customer</a></li>
<li class="dropdown"><a href="#" data-toggle="modal" data-target="#modal-2">New Category</a></li>
</ul>
</div>
A bit of guessing here: I see your container's name is "Modalmap"
. This makes me think that you are showing your map in a modal container.
I'm also guessing that the height and width of that "Modalmap"
(which is leaflet's container) are being dynamically set, when modal has showed up. Maybe that gives some problems to your leaflet map, because leaflet calculates its width and height when it initializes, based on it's parent width and height. And thats happening when your modal is not showing and it maybe has small values as width and height, and these small values end up being leaflet's width and height.
You can try to call for leaflet map to "refresh" its size after you show the modal and the modal has got its correct height and width.
Try this, right after the line you trigger your modal to be shown:
setTimeout(function(){ map.invalidateSize()}, 500);
This is going to force leaflet to re-calculate its size after 500 ms. (I guess 500ms are enough for your modal to be shown). Try a bigger value if it doesn't work.
Update: For bootstrap 3 just place this in your code
$('body').on('shown.bs.modal', function (e) {
setTimeout(function(){ map.invalidateSize()}, 500);
})
Tip:I suggest you dont use body
as selector of jquery as this is going to trigger the code for all your modals. Use a more specific selector that you have in your markup
More info here Calling a function on bootstrap modal open