默认情况下,我有一个 V3 map 加载并以特定的经度/纬度为中心。加载后,用户可以输入他们的地址以获取前往该地点的路线。发生这种情况时, map 会调整大小以适应其左侧的方向框。因此,路线在 map 窗口中偏离中心。我尝试了以下代码,我认为它在逻辑上应该可行,但无济于事。
新认识:如果我以任何方式调整窗口大小,它就会开始按预期工作。
发现问题:我需要在调整 map 容器的大小后触发 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-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 开始没有任何效果
最佳答案
您已经找到了我要说的答案。调整大小事件对于在您更改 map 容器(或可能是其父级)时正确处理非常重要。就我而言,我在两个选项卡( map 和行车路线)之间切换。起初, map 会在 map 选项卡中正确显示,但切换到方向并返回 map 会导致显示不正常。
如果您的 map 只在一个 Angular (在我的例子中是左上角)显示一个小图 block ,其余部分为空白,您可能需要触发调整大小触发器。
关于javascript - 呈现路线后,将 V3 Google map 置于 route 心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365469/