【发布时间】:2011-07-18 22:31:40
【问题描述】:
默认情况下,我有一个 V3 地图加载并以特定经度/纬度为中心。加载后,用户可以输入他们的地址以获取到该点的路线。发生这种情况时,地图会调整大小以适应其左侧的方向框。因此,路线在地图窗口中偏离中心。我尝试了以下代码,我认为它在逻辑上应该可以工作,但无济于事。
新认识:如果我以任何方式调整窗口大小,它就会开始按预期工作。
发现问题:我需要在调整地图容器大小后触发google.maps.event.trigger(map, 'resize')。
directionsService.route(query, function(result,status) {
if (status === google.maps.DirectionsStatus.OK) {
// This sets the directions container to display:block and resizes the map
document.getElementById('map-container').className = "directions";
directions.setDirections(result);
var bounds = result.routes[0].bounds;
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
} else {
alert("");
}
});
2018 年 5 月 22 日更新
随着 Maps JavaScript API 3.32 版中的新渲染器版本的发布,调整大小事件不再是 Map 类的一部分。
文档说明
调整地图大小时,地图中心固定
全屏控件现在保留居中。
不再需要手动触发调整大小事件。
来源:https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize"); 从版本 3.32 开始没有任何效果
【问题讨论】:
-
一旦你调用 fitBounds 它应该基于 LatLngBounds 居中所以你不应该需要 setCenter
-
是的,我在最后的努力中添加了 setCenter()。无论有没有它,它都不会像预期的那样居中。
-
完全误读了“调整大小”地图部分。很高兴它成功了
-
@Justin 你能回答你自己的问题吗?谢谢。
标签: javascript google-maps google-maps-api-3