如何替换Google Maps API默认信息窗口为自定义样式?
解决@react-google-maps/api中POI点击默认信息窗口弹出问题
方法一:拦截原生事件阻止默认窗口
在你的handleOnClick函数中,当检测到点击对象带有placeId时,调用event.stop()即可直接阻止原生信息窗口弹出。这个方法能从事件源头拦截默认行为,不会出现默认窗口先显示再被覆盖的情况:
修改后的代码:
async function handleOnClick(event) { // 拦截POI点击的默认行为 if (event.placeId) { event.stop(); } setContent(undefined); const latitude = event.latLng.lat(); const longitude = event.latLng.lng(); if (event.placeId) { const request = { placeId: event.placeId, fields: ['name', 'formatted_address', 'place_id', 'geometry', 'photo'], }; const placesService = new google.maps.places.PlacesService(map); placesService.getDetails(request, (place, status) => { if (status === 'OK') { const info = ( <InfoWindow position={{ lat: place?.geometry?.location?.lat(), lng: place?.geometry?.location?.lng(), }} onCloseClick={() => setContent(undefined)} > <div> <h3>{place.name}</h3> <div className='photo-gallery'> {place?.photos.map((photo, index) => { // 添加key属性避免React列表渲染警告 return <img key={index} className='photo' src={photo.getUrl()} />; })} </div> </div> </InfoWindow> ); setContent(info); } }); } }
说明:event.stop()是Google Maps原生事件对象的方法,会终止事件传播并取消所有默认行为,包括原生信息窗口的弹出逻辑。
方法二:全局禁用POI默认窗口(可选)
如果希望整个地图范围内的POI点击都不触发默认窗口,可以在地图初始化时监听poi-click事件并拦截:
const onMapLoad = (mapInstance) => { // 全局拦截所有POI点击的默认行为 mapInstance.addListener('poi-click', (event) => { event.stop(); }); };
将上述回调传入Map组件的onLoad属性即可,之后所有POI点击都会跳过默认窗口逻辑,完全由你的自定义事件处理。
额外提示
- 确保
InfoWindow组件通过状态(如你的content变量)控制渲染,在Map组件内部直接渲染{content}即可。 - 处理POI图片列表时,务必添加
key属性,避免React抛出列表渲染警告。
内容的提问来源于stack exchange,提问作者Lehi
相关产品推荐
相关产品推荐

