Showing Google Map inside a Bootstrap modal window

If you try to add a Google Map inside a Bootstrap modal window you will get some strange behaviors. This is because you need to trigger a resize event on the map when the div changes size (take a look at the Google Maps docs).

We already have seen how to add a Google Map using API 3 (without any plugins). Now, to get a well working map inside a Bootstrap modal window we only need to add this snippet at the bottom of initializeMap function:

Javascript (and Coffeescript)

  initializeMap = function(id) {

    ...

    // When modal window is open, this script resizes the map and resets the map center
    $("#modalWindowId").on("shown.bs.modal", function(e) {
      google.maps.event.trigger(map, "resize");
      return map.setCenter(markerLatLng);
    });
  }
  initializeMap = ->

    ...

    # When modal window is open, this script resizes the map and resets the map center
    $("#modalWindowId").on "shown.bs.modal", (e) ->
      google.maps.event.trigger map, "resize"
      map.setCenter(markerLatLng);

shown.bs.modal is a Bootstrap event that check when the modal is open (check out the Events section of Boostrap modal docs for more info)

  • Jayden Lawson

    Thanks – but you should add an example. Would be much better.

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo