I’m using the Google Maps API v2. I add markers to the map and then zoom to fit those markers. This works fine if the map is visible I do this. But if not – for example, if I have a tabstrip, and the map’s tab isn’t selected when the page loads – then when I do show the map, the zoom level and center are wrong.
Here’s a simple test case (uses jQuery):
<script type="text/javascript">
var scale = Math.random() * 20;
$(document).ready(function() {
var $container = $('#container');
// $container.hide();
var map = new GMap2($('#map')[0]);
$container.show();
var markerBounds = new GLatLngBounds();
for (var i = 0; i < 10; i++) {
var randomPoint = new GLatLng(38.935394 + (Math.random() - 0.5) * scale, -77.061382 + (Math.random() - 0.5) * scale);
map.addOverlay(new GMarker(randomPoint));
markerBounds.extend(randomPoint);
}
map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
});
</script>
<div id="container">
<div id="map" style="margin: 100px; width: 450px; height: 300px;"></div>
</div>
This works fine as is, but if you uncomment $container.hide() it’s all whacked out.
Is there a way to get the Google Maps API to work properly on a div that’s not visible?
All you would need to do is to create the
GMaps2()before anything else. You can thenhide()the container, add the points, get thegetBoundsZoomLevel(),show()it again, and it should work fine.Try the following: