0

Using Leaflet with Rails through webpacker I cannot get to the right setup to avoid an "Error: Map container not found" for the maps that are not actually displayed.

i have cleaned my web packer config and it's not a standard config.

maps are rendered with:

<div class="map-wrapper-300">
  <%= tag.div nil, id: 'map-contact', class:"h-100" %>
</div>

and in my javascript folder I have the following code (javascript/map-contact.js)

function buildMap(lat,lon)  {

  document.getElementById('map_contact').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
  console.log("script #1: %o", document.getElementById('map_contact'));
  console.log("script #3: %o", document.getElementsByClassName('map-wrapper-300'));

  var map = new L.Map('map', {
      dragging: false,
      tap: false,
      scrollWheelZoom: false
  });
  map.setView(new L.LatLng(lat,lon), 9 );

  var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
                  osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,' +
                      ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
  osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});

  map.addLayer(osmLayer);

  var circle = L.circle([lat, lon], {
      color: 'red',
      fillOpacity: 0.5,
      radius: 500
  }).addTo(map);

  circle.bindPopup("We are located here.");
}

var element = document.getElementsByClassName('map-wrapper-300');
if (element.length > 0 ) {
  document.addEventListener("turbolinks:load", function() {
      buildMap(47.75,7.3333);
  });
}

I am trying to render this map only if the div.class is found. therefore using the conditional rendering if map-wrapper-300 is found (element.length > 0).

I think the if statement is assessed before the the map loads. any hints ?

Thierry
  • 111
  • 2
  • 14
  • Please share more info, including your package.json, application.js and any changes you’ve made to your webpacker config so that others can reproduce the problem. – rossta Mar 30 '20 at 12:53

1 Answers1

0

I am unsure this is the best solution but I got rid of the errors. i solved the issue by setting a id="leaflet_custom_id" on the page where a map is rendered and by adding the following:

function buildMap(lat,lon)  {}

document.addEventListener("turbolinks:load", function() {
  if (document.getElementById('leaflet_contact') == null) {
    //console.log('true')
  }
  else {
    buildMap(lat,lon);
  }
});

this helped a lot: refresh leaflet map: map container is already initialized

Thierry
  • 111
  • 2
  • 14