I've had a lot of trouble getting a map centred correctly inside a Bootstrap tab that is hidden. The following should work for any map with a containing element that is hidden on page load.
The problem is the centre point defined for the map is actually in the bottom left corner of the map, due to the initial dimensions of the containing element being 0px x 0px when the map is initialised.
Everywhere I searched proposed triggering a resize using google.maps.event.trigger(my_map, 'resize');, but for me this did absolutely nothing about correcting the map centre point.
So here I would just like to document the solution I have come to, which adjusts the centre points of the map to the intended one, at the point when the tab containing the map is shown.
// Execute function on Bootstrap tab shown event
$('a[href="#map"]').on('shown.bs.tab', function(e)
{
var center = map.getCenter(), // current (incorrect) map centre
offsetX = -0.5, // move centre one half map width right
offsetY = 0.5, // move centre one half map height down
span = map.getBounds().toSpan(); // the size of the map canvas
var newCenter = {
lat: center.lat() + span.lat() * offsetY,
lng: center.lng() + span.lng() * offsetX
};
map.setCenter(newCenter);
});
Apologies for this solution not being specific for IvoryGoogleMap but I felt it was good to document this here for future Google searchers.
I've had a lot of trouble getting a map centred correctly inside a Bootstrap tab that is hidden. The following should work for any map with a containing element that is hidden on page load.
The problem is the centre point defined for the map is actually in the bottom left corner of the map, due to the initial dimensions of the containing element being 0px x 0px when the map is initialised.
Everywhere I searched proposed triggering a resize using
google.maps.event.trigger(my_map, 'resize');
, but for me this did absolutely nothing about correcting the map centre point.So here I would just like to document the solution I have come to, which adjusts the centre points of the map to the intended one, at the point when the tab containing the map is shown.
Apologies for this solution not being specific for IvoryGoogleMap but I felt it was good to document this here for future Google searchers.