首页 > 解决方案 > Leaflet map not updating view

问题描述

I'm trying to display a map in a modal, so when I close it and open a new one, the map shows always the first location instead of the current modal. I reset the map, but still nothing happens.

Before open the modal, I print the map:

$('#openMap').on($.modal.BEFORE_OPEN, function(event, modal) {
   printMap('map', coord);
});

After closing modal, I remove the map container:

$('#openMap').on($.modal.AFTER_CLOSE, function(event, modal) {
   $('#map').remove();
});

This is printMap function code:

var map = null; // Global variable
function printMap(map_id, coord) {
    const mapbox_token = '...';

    if(map) {
        map.eachLayer(function (layer) {
          map.removeLayer(layer);
        });
        map.off();
        map.remove();
        map.on('viewreset', function (e) {
           console.log('Reset view...') // Do not showed
        })
        delete map;
        map = null;
        // none of these work
    }

  // Load map
  map = L.map(map_id).setView(coord, 13);

  // Create the tile layer with correct attribution
  L.tileLayer(...).addTo(map);

  // Add marker
  L.marker(coord).addTo(map);

  // Invalidate size for modal
  $('.modal').on($.modal.OPEN, function (event, modal) {
    setTimeout(function(){ map.invalidateSize()}, 0);
  });
}

Hope somebody could help me! Thanks in advance!

标签: javascriptleaflet

解决方案


Your map variable is local to your printMap function, i.e. whenever you execute that function, it gets a new allocation for its local variable. Hence map is always uninitialized when you check it.

Then you may have a scoping issue for your coords value when you use it to attach your modal before open listener.


推荐阅读