我有一张地图,上面有一个半透明的搜索栏。我还有一堆带有信息窗口的标记。
问题是谷歌地图自动平移功能显然没有考虑我的搜索栏,因此如果我的标记太靠近顶部,信息窗口的一部分就会被搜索栏覆盖。
是否可以以某种方式指定信息窗口距地图顶部的最小距离?
我还考虑使用标记的位置来限制地图的边界,但在我的情况下,标记也可能最终位于搜索栏下方,所以这不是一个选项。
有什么想法吗?谢谢您的宝贵时间!
存在一个名为 Snazzy Info Window 的库,可以用来代替通常的 InfoWindow。然后,您可以将选项 edgeOffset(以像素为单位)传递给该对象,瞧,问题解决了。希望这对将来的人有帮助!
我基于 Snazzy Info Window 库编写了信息窗口重新定位代码。
const panMap = () => {
const offsetTop = 20;
const offsetRight = 20;
const offsetBottom = 60;
const offsetLeft = DeliveryHelper.isMobile ? 20 : 300;
const mapContainerRect = document.querySelector('.gm-style')?.getBoundingClientRect();
const infowindowRect = document.querySelector('.gm-style-iw.gm-style-iw-c')?.getBoundingClientRect();
if (mapContainerRect === undefined || infowindowRect === undefined) return
const mapRect = {
top: mapContainerRect.top + offsetTop,
right: mapContainerRect.right - offsetRight,
bottom: mapContainerRect.bottom - offsetBottom,
left: mapContainerRect.left + offsetLeft
}
mapContainerRect.width = mapRect.right - mapRect.left
mapContainerRect.height = mapRect.bottom - mapRect.top
let dx = 0
let dy = 0
if (mapRect.left >= infowindowRect.left) {
dx = infowindowRect.left - mapRect.left
} else if (mapRect.right <= infowindowRect.right) {
dx = infowindowRect.left - (mapRect.right - infowindowRect.width)
}
if (mapRect.top >= infowindowRect.top) {
dy = infowindowRect.top - mapRect.top
} else if (mapRect.bottom <= infowindowRect.bottom) {
dy = infowindowRect.top - (mapRect.bottom - infowindowRect.height)
}
if (dx !== 0 || dy !== 0) {
map.panBy(dx, dy)
}
}
您必须在信息窗口呈现后调用它
const domReadyListener = infowindow.addListener('domready', () => {
panMap();
google.maps.event.removeListener(domReadyListener);
});
并且在地图移动完成渲染之后(我仅在缩放更改后调用它,并在 zoom_changed 事件之后使用 idle 事件,因为由于某种原因它在移动渲染完成之前触发)
map.addListener('zoom_changed', () => {
const idleListener = map.addListener('idle', () => {
setTimeout(panMap, 10);
google.maps.event.removeListener(idleListener);
});
});