I am trying to hide/show Google Maps by switching between display:none; and display:inherit;. When I apply display:inherit to Google Maps, part of the map gets cropped and I am unsure why. How would I fix this while still using display:none;?
//HTML
<button id="toggleMap">Toggle Google Map</button>
<button id="toggleImage">Toggle Image</button>
<div id="image">
<img src="http://jdm-digital.com/wp-content/uploads/2012/04/google-jquery-opt-465x346.jpg">
</div>
<div id="map" style="width:500px; height:500px; display:none;">
<div id="map_canvas" style="height:100%;"></div>
</div>
//JavaScript
$('#toggleImage').click(function() {
$('#image').css('display', 'inherit');
$('#map').css('display', 'none');
});
$('#toggleMap').click(function() {
$('#image').css('display', 'none');
$('#map').css('display', 'inherit');
});
If you create a map while it’s hidden the API doesn’t know how big it should be because the browser reports it has zero size. The API only loads enough tiles for a zero-size map, and positions the centre at (0,0) — the top-left corner.
When you unhide the map, tell the API to get the new size by triggering the resize event:
Documentation — scroll down to Events.