我将“mapwrap”div 设置为 400px x 400px,在其中我将 Google“ map ”设置为 100% x 100%。所以 map 以 400 x 400 像素加载,然后使用 JavaScript 我将“mapwrap”的大小调整为屏幕的 100% x 100% - 谷歌地图按我的预期调整到整个屏幕,但图 block 在右手边缘之前开始消失页面。
我可以调用一个简单的函数来使 Google map 重新调整为更大尺寸的“mapwrap”div 吗?
最佳答案
对于 Google map v3,您需要以不同方式触发调整大小事件:
google.maps.event.trigger(map, "resize");
请参阅调整大小事件的文档(您需要搜索“调整大小”一词):http://code.google.com/apis/maps/documentation/v3/reference.html#event
更新
这个答案已经存在很长时间了,所以一个小演示可能是值得的,虽然它使用 jQuery,但没有真正需要这样做。
$(function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map($("#map-canvas")[0], mapOptions);
// listen for the window resize event & trigger Google Maps to update too
$(window).resize(function() {
// (the 'map' here is the result of the created 'var map = ...' above)
google.maps.event.trigger(map, "resize");
});
});
html,
body {
height: 100%;
}
#map-canvas {
min-width: 200px;
width: 50%;
min-height: 200px;
height: 80%;
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
2018-05-22 更新
随着 Maps JavaScript API 3.32 版中新渲染器的发布,调整大小事件不再是 Map
类的一部分。
文档说明
When the map is resized, the map center is fixed
The full-screen control now preserves center.
There is no longer any need to trigger the resize event manually.
来源:https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
从版本 3.32 开始没有任何效果
关于javascript - 加载后如何使用 JavaScript 调整 Google map 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743214/