代码改变世界

动态重置google地图尺寸(Resize a Google Map Dynamically)

2012-04-04 19:53  iBlog  阅读(746)  评论(0编辑  收藏  举报

FROM http://techxplorer.com/2011/10/04/resize-a-google-map-dynamically/

Last year I grappled with the issue of how to resize a google map dynamically. With my work on the MARQues project I’ve needed to work through the same issue again, although this time a little differently.

My user interface design for the website that uses the Film Weekly dataset, the first dataset to use the MARQues system, is simpler than the design I was working on last year. It is basically a three row layout with a header, footer, and the middle section devoted to the map. In this way the map becomes a central part of the design.

I needed to use JavaScript again to achieve the basic layout, while CSS can be used to push to the footer down to the bottom of the page, the middle row won’t resize to fill the available space. My JavaScript is based on this stack overflow q&a.

First is the updated resize function:

//dynamically resize the map
function resizeMap() {

// calculate new size and apply it
var mid = document.getElementById('map_container');
var foot = document.getElementById('footer');

//mid.style.height = ((foot.offsetTop+foot.clientHeight)-(mid.offsetTop+mid.clientHeight))+'px';
mid.style.height = ((foot.offsetTop) - (mid.offsetTop))+'px';

// trigger a resize event on the map so it reflects the new size
if(map != null) {
google.maps.event.trigger(map, 'resize');
}
}

 

 

Note that in my version the height calculation is a little different as the footer height already appears to impact the height of the middle row and so doesn’t need to be taken into account. Please also note that I’m using version of the Google Maps API.

The second part of the puzzle is to call the function when the page loads and when the window resizes. The core of all of my JavaScript in the past few years has been jQueryand so I use it here as well.

//populate the page
$(document).ready(function() {

//resize the map container
resizeMap();

// bind resize map function to the resize event for the window
$(window).resize(function() {
resizeMap();
});

// continue with the initialisation of the map
});