Leaflet GeoJSON Polygon Resize – Resizing GeoJSON Polygon Map with Browser Window in Leaflet

leaflet

I am trying to make a map of just geojson boundaries, no basemap/tiles and want it to scale up/down when the window is resized to keep the full map visible and as large as possible.

While the map.fitBounds(layer.getBounds()) in window.addEventListener('resize', function(event) works somewhat, it can get stuck remaining small, cut off some of the edges being too large and is overall wonky.

example jsfiddle: https://jsfiddle.net/6yt4ekxL/6/

var mapOptions = {
  attributionControl: false,
  zoomControl: false,
  zoomSnap: 0.02,
  zoomDelta: 0.08,
  scrollWheelZoom: false,
  touchZoom: false,
  doubleClickZoom: false,
  boxZoom: false,
  keyboard: false,
  dragging: false,
  background: "None",
};

var mapStyle = {
  color: "#1890ff",
  weight: 1,
  opacity: 0.85,
};


var map = L.map('map', mapOptions).setView([0, 0], 3);

layer = L.geoJSON(basemap, {
    style: mapStyle,
  })

map.addLayer(layer);
map.fitBounds(layer.getBounds());

window.addEventListener('resize', function(event) {
    map.fitBounds(layer.getBounds());
}, true);

Best Answer

Problem is that while resizing window, resize events are continuously fired and new map.fitBounds requests interfere with the ones being executed.

Solution is to use setTimeout to delay execution of map.fitBounds a bit and cancel execution if new request is issued while waiting.

Relevant code could then look something like this:

var timeoutId = null;

window.addEventListener('resize', function(event) {
  if (timeoutId) clearTimeout(timeoutId);
  timeoutId = setTimeout(function() {
    map.fitBounds(layer.getBounds());
    timeoutId = null;
  }, 50);
}, true);
Related Question