javascript - 加载后如何使用 JavaScript 调整 Google map 的大小?

标签 javascript css google-maps

我将“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/

相关文章:

javascript - BigText 的垂直间距(行高)

css - 我如何向程序员解释 CSS 定位比基于表格的布局有很多好处?

html - 更改下拉菜单的大小

css - 使用 jquery 移动和谷歌地图时的样式问题——需要刷新以适合

javascript - 使用 AJAX 的数据表,求和并添加总页脚

javascript - 你如何加载 2 个 javascript 文件,它们之间可能有公共(public)变量并在 HTML 页面上访问它?

javascript - 通过 id 获取最近的元素

javascript - 在我的函数中更改 css 背景颜色

javascript - Tweet 按钮和信息窗口

android - 谷歌地图未在手机上显示但可在模拟器上使用