如何在创建Google Maps标记时阻止地图自动移动?
问题
已成功在谷歌地图上显示标记并默认打开对应的InfoWindow,但遇到一个问题:当当前地图视图不在标记的显示范围内时,地图会自动移动以显示标记。更新标记位置时,希望阻止地图自动移动,仅让标记静默生成。
当前实现代码:
for (const location of this.transformedData) { const marker = new google.maps.Marker({ position: new google.maps.LatLng(location.lat, location.lng), map: this.map, title: location.addr, icon: { url: location.url, scaledSize: new google.maps.Size(50, 50) }, center: this.center }); const infowindow = new google.maps.InfoWindow({ content: location.infoWindowContent }); infowindow.open(this.map, marker); this.markers.push(marker); }
曾尝试在循环结束后重置地图中心,但并未生效:
this.currentMapCenter = this.map.getCenter(); // ... 循环逻辑 // 循环结束后 if (this.currentMapCenter) { this.map.setCenter(this.currentMapCenter); }
解决方案
问题根源在于调用infowindow.open()时,谷歌地图的InfoWindow默认会自动平移地图,让标记和信息窗口处于可见区域。事后重置地图中心之所以无效,是因为自动平移的操作是异步的,你的重置代码可能在自动平移完成前就执行了,被后续的平移操作覆盖。
正确的解决方式是在创建InfoWindow时,添加disableAutoPan: true配置项,直接禁用自动平移功能:
修改后的代码:
for (const location of this.transformedData) { const marker = new google.maps.Marker({ position: new google.maps.LatLng(location.lat, location.lng), map: this.map, title: location.addr, icon: { url: location.url, scaledSize: new google.maps.Size(50, 50) }, center: this.center }); const infowindow = new google.maps.InfoWindow({ content: location.infoWindowContent, // 添加这一行,禁用自动平移 disableAutoPan: true }); infowindow.open(this.map, marker); this.markers.push(marker); }
这样创建并打开InfoWindow时,地图就不会自动移动,标记会静默生成在对应位置,同时保持当前地图视图不变。
内容的提问来源于stack exchange,提问作者bovcu13
相关产品推荐
相关产品推荐

