Render Google Map Inside jQuery Carousel or Bootstrap Modal

16 January 17 Ben Dickman

I have worked quite alot recently with Google Maps in various forms, from simple maps with a single pin to custom drawing functionality. Anyway, I often found issues with the map not fully rendering and thought it would be useful to document in a post. I know this will help someone out there and it has got me out of a few frustrating situations in the past.

So what is the issue? When you render a Google map in a modal or carousel I find it will normally not fully draw the complete map. There will be no JavaScript errors in the console and it really does seem odd. The first time I came across this I also noticed that if I adjust the size of the browser window the map would render as expected. Essentially what is happening here is, in every scenario the map is hidden on page load and so has no dimensions. To get around this issue you will need to call resize on the map when it is visible.

The following code can be used to check if the map is the current slide in the carousel and call resize to correctly render the map.

$('#carousel-id').on('slid.bs.carousel', function (e) {
    if($('.item.active').find("#map-id").length == 1) {
      google.maps.event.trigger(map, "resize");
    }
 });

The following code can be used to check if the Bootstrap modal is visible and again trigger the resize.

$('#modal-id').on('shown.bs.modal',function(){
  google.maps.event.trigger(map, "resize");
});

They are very simple extracts of code but could save you some time and frustration.

See you next time, Ben.