Resizing a leaflet map on container resize

后端 未结 6 887
渐次进展
渐次进展 2020-12-08 02:30

I have a

containing a leaflet map. Upon certain events the height of the
will be altered. I\'d like for the map to resize t
6条回答
  •  时光取名叫无心
    2020-12-08 03:04

    I came across this question today and wanted to provide an updated answer based on 2020 Browser API. This example uses the Browser's ResizeObserver to monitor the size of the div that Leaflet is mounted too. Assuming the following HTML Snippet:

    With the following JavaScript:

    const mapDiv = document.getElementById("map");
    const map = L.map(mapDiv).setView([51.505, -0.09], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    
    const resizeObserver = new ResizeObserver(() => {
      map.invalidateSize();
    });
    
    resizeObserver.observe(mapDiv);
    

    This should monitor the map div, and call the invalidateSize() method on the Leaflet map when the map div size changes. This approach allows you to handle the resizing "closer" to the map code, rather than trying to rely on window resize events or listening for changes triggered elsewhere in the application.

    Obviously the CSS for the map div itself will need to ensure that it resizes in whatever way you want it to. This code snippet will ensure the Leaflet is appropriately updated when that happens.

提交回复
热议问题