0

I'm having problems getting the map to display in a boostrap 5 modal. It works outside the modal. Inside the modal the default Layers show but not the map itself. My js function

function loadMap(zoom, lat, lng) {
  var mapContainer = document.createElement('div');
  mapContainer.style.height = '300px';
  mapContainer.style.width = '600px';
  document.getElementById('mapInsideModal').appendChild(mapContainer);
   
  var defaultLayers = platform.createDefaultLayers();

  // Instantiate the map:
  var map = new H.Map(mapContainer, defaultLayers.vector.normal.map, {
    zoom: zoom,  center: {   lng: lng,  lat: lat,},
  });
  // add a resize listener to make sure that the map occupies the whole container
  window.addEventListener('resize', function () {map.getViewPort().resize();});
  // Create the default UI:
  var ui = H.ui.UI.createDefault(map, defaultLayers);
  
}

I created an id <div id="mapInsideModal"></div> in the Bootstrap modal html where I want the map displayed.

Nimantha
  • 6,405
  • 6
  • 28
  • 69

1 Answers1

0

By default the document.getElementById('mapInsideModal') is display:none therefore the map object is not initialized properly.

First create mapContainer with css style like "position: absolute; left: -99999px;"

var mapContainer = document.createElement('div');
mapContainer.style.position = "absolute";
mapContainer.style.left = "-99999px";

Add mapContainer element to the body element.

Your map will be not shown therefore you need to do this document.getElementById('mapInsideModal').appendChild(mapContainer); and set style css left: 0px; for mapContainer element inside of shown.bs.modal event - see please on the bottom of page https://getbootstrap.com/docs/5.1/components/modal/

shown.bs.modal - This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the relatedTarget property of the event.