Leaflet – How to Fix Invalidate Size Not a Function Error

leaflet

I have a leaflet map that is nested within a div. I have tabs. When the tab that contains the leaflet map is the default tab, the map loads and works correctly. When it is not, it does not load correctly. It does not load all tiles.

If I resize the page, it then loads. I am trying map.invalidateSize but get an is not a function error. Leaflet object properties at the time the invalidateSize is invoked are as follows:

_leaflet_dblclickdblclick4_2:r()
_leaflet_events: {…}
_leaflet_id: 3
_leaflet_pointerdowndblclick4_2:n()
_leaflet_pointerupdblclick4_2:o()
_leaflet_touchstarttouchstart15_16()
_leaflet_touchstarttouchstart23_24()
accessKey: ""
accessKeyLabel: ""
align: ""
assignedSlot: null
attributes: NamedNodeMap(3)
baseURI: "http://localhost/RG/#10/44.1206/-122.3067"
childElementCount: 3
childNodes: NodeList(4)
children: HTMLCollection(3)
classList: DOMTokenList(6)
className: "leaflet-container leaflet-touch leaflet-fade-anim leaflet-grab leaflet-touch-drag leaflet-touch-zoom"
clientHeight: 345
clientLeft: 0
clientTop: 0
clientWidth: 1036
contentEditable: "inherit"
contextMenu: null
dataset: DOMStringMap(0)
dir: ""
draggable: false
firstChild: #text
firstElementChild: div.leaflet-pane.leaflet-map-pane
hidden: false
id: "map"

I have the following code:

function openPage(pageName, elmnt, color) {

 // Hide all elements with class="tabcontent" by default */
 var i, tabcontent, tablinks;
 tabcontent = document.getElementsByClassName("tabcontent");
 for (i = 0; i < tabcontent.length; i++) {
     tabcontent[i].style.display = "none";
 }

 // Remove the background color of all tablinks/buttons
 tablinks = document.getElementsByClassName("tablink");
 for (i = 0; i < tablinks.length; i++) {
     tablinks[i].style.backgroundColor = "";
 }

 // Show the specific tab content
document.getElementById(pageName).style.display = "block";


if ([pageName] == "Flow") {
document.getElementById("FlowLog").style.display = "block";
document.getElementById("lmap").style.visibility = "visible";
setTimeout(function(){ map.invalidateSize(true)}, 400);
}
}

 var map = L.map('lmap', {

//  preferCanvas: true,  //for leaflet image plugin
    measureControl:true,
    zoomControl:true, maxZoom:45, minZoom:1,
    center: ([44.120, -122.5951]),
    zoom: 11
   })

Best Answer

Your map variable seems to be a DOM element, not the leaflet instance.

You need to call the leaflet API on a map instance, which is linked to the dom element.

var map = L.map('my-map'); // my-map is the ID of your DOM map container
map.invalidateSize();      // should work then