2014年5月6日火曜日

Google Maps JavaScript API v3でマップのサイズを変更する方法

Google Maps JavaScript API v3でマップのサイズを変更する方法をメモしておきます.

マップのサイズを動的に変更すると,次のように一部が欠けているような感じになることがあります.

これを起こさないようにするには,サイズの変更後にマップに対して「resize」イベントを送ればいいみたいです. そうすると,次のように一部が欠けることなく,マップのサイズを変更することができます.

試しに作ってみたコードは以下のとおりです.

<!DOCTYPE html>
<html>
<head>
<title>Google Maps API v3 Map Resize</title>
<style>
html {
height: 100%;
}
body {
position: relative;
height: 100%;
margin: 0;
}
#map {
position: absolute;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<button id="shrink_button">-</button>
<button id="expand_button">+</button>
<div id="map"></div>
<script>
var x = 40;
var y = 40;
var width = 20;
var height = 20;
var mapElement = document.getElementById('map');
mapElement.style.left = x + "%";
mapElement.style.top = y + "%";
mapElement.style.width = width + "%";
mapElement.style.height = height + "%";
var mapOptions = {
center: new google.maps.LatLng(35.0, 135.0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapElement, mapOptions);
var shrinkButtonElement = document.getElementById('shrink_button');
shrinkButtonElement.addEventListener("click", function () {
x += 5;
y += 5;
width -= 10;
height -= 10;
mapElement.style.left = x + "%";
mapElement.style.top = y + "%";
mapElement.style.width = width + "%";
mapElement.style.height = height + "%";
google.maps.event.trigger(map, 'resize');
});
var expandButtonElement = document.getElementById('expand_button');
expandButtonElement.addEventListener("click", function () {
x -= 5;
y -= 5;
width += 10;
height += 10;
mapElement.style.left = x + "%";
mapElement.style.top = y + "%";
mapElement.style.width = width + "%";
mapElement.style.height = height + "%";
google.maps.event.trigger(map, 'resize');
});
</script>
</body>
</html>