How to add google map to bootstrap modal

I am using the Google Embed map option to embed the map in Bootstrap Modal, but the modal is displayed with the map shape, but only part of the map is displayed and the rest are grayed out.

Here is the code I used:

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Click For Map</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

      

Here's the jquery I added

$('#myModal').on('shown.bs.modal', (function() {
  var mapIsAdded = false;

  return function() {
    if (!mapIsAdded) {
      $('.modal-body').html('<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d9808.974038062652!2d4.3244048859985185!3d52.07529689519739!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1snl!2snl!4v1419588821379" width="100%" height="400" frameborder="0" style="border:0"></iframe>');

      mapIsAdded = true;
    }    
  };
})());

      

I can't seem to find the exact problem for this, any help would be greatly appreciated.

+3


source to share


1 answer


This is due to modal existence display: none

initially. I think this makes Google Maps JavaScript iframe

incapable of working properly internally . To verify this, try removing the class .modal

and opening the modal.

The simplest solution might be to increment the iframe when the modal is first opened using an event shown.bs.modal

:

$('#myModal').on('shown.bs.modal', (function() {
  var mapIsAdded = false;

  return function() {
    if (!mapIsAdded) {
      $('.modal-body').html('<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d9808.974038062652!2d4.3244048859985185!3d52.07529689519739!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1snl!2snl!4v1419588821379" width="100%" height="400" frameborder="0" style="border:0"></iframe>');

      mapIsAdded = true;
    }    
  };
})());

      



or see this Codepen

Next to this iframe

has a fixed attribute width="800"

. I suggest you change this to width="100%"

as the modal does not have a fixed width.

+4


source







All Articles