John Beasley
John Beasley

Reputation: 3081

jQuery and Leaflet gives error "map container is already initialized"

Note: I tried not to duplicate this question. I attempted to use answers from previous posts to no avail.

I keep getting the error that reads:

Uncaught Error: Map container is already initialized.

Using the following code:

$('#example1').on('click', 'tr > td > a.loadMap', function(e) 
{
  e.preventDefault();
  var $dataTable = $('#example1').DataTable();
  var tr = $(this).closest('tr');
  var data = $dataTable.rows().data();

  var actramp = $(this).attr('data-actramp');
  var actimpdel = $(this).attr('data-actimpdel');   
  var actramplat = parseFloat($(this).attr('data-actramplat'));
  var actramplng = parseFloat($(this).attr('data-actramplng'));
  var actdellat = parseFloat($(this).attr('data-actdellat'));
  var actdellng = parseFloat($(this).attr('data-actdellng'));
  var actreclat = parseFloat($(this).attr('data-actreclat')); 
  var actreclng = parseFloat($(this).attr('data-actreclng')); 

  $('#actionMatchbackModal').modal('show');

  $("#actionMatchbackModal").on("shown.bs.modal", function () {
    initMap(actramp, actimpdel, actexpreceipt, actramplat, actramplng, actreclat, actreclng, actdellat, actdellng); 
  });
});

function initMap(actramp, actimpdel, actexpreceipt, actramplat, actramplng, actreclat, actreclng, actdellat, actdellng)
{
  var map = L.map('map').setView([actreclat,actreclng], 8);

  // vvv this was an answer provided from another post vvv
  if (map != undefined) {
    map.remove();
  }
  // ^^^ but the map stopped loading completely ^^^

  map.invalidateSize();

  L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=zAlHsNvo6jxv4ENZxW3R', {
    attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'
  }).addTo(map);
}

What can I add/remove to the above code that will fix the "map container is already initialized" error?

Upvotes: 0

Views: 4373

Answers (1)

peeebeee
peeebeee

Reputation: 2618

You're on the right lines, but you should remove() the map before you (re)-initialize it - and make sure the scope of the map variable is correct. Like this

var map;

...

function initMap(actramp, actimpdel, actexpreceipt, actramplat, actramplng, actreclat, 
actreclng, actdellat, actdellng)
{

    if (map != undefined) map.remove();
    map = L.map('map').setView([actreclat,actreclng], 8);

    ...

}

Upvotes: 2

Related Questions