You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Google Maps API:鼠标悬停Marker时所有信息窗口异常打开问题

解决React Google Maps API悬停Marker时仅打开对应信息窗口的问题

你的问题出在使用了全局布尔状态showMarker,所有Marker都依赖这个状态切换显示,导致鼠标悬停任意一个Marker时,所有Marker都会替换成InfoWindow。以下是修正方案:

步骤1:修改状态管理

将全局布尔状态改为记录当前激活的Marker唯一标识(比如酒店ID或数组索引):

// 优先用hotel的唯一id,没有则用数组索引i
const [activeMarkerId, setActiveMarkerId] = useState(null);

步骤2:调整渲染逻辑

Marker需要始终显示,仅根据激活状态控制对应InfoWindow的显示,修改循环内的代码:

{markers?.map((hotel, i) => (
  <React.Fragment key={i}>
    <Marker
      position={{ lat: hotel.lat, lng: hotel.lng }}
      onMouseOver={() => setActiveMarkerId(hotel.id || i)}
      onMouseOut={() => setActiveMarkerId(null)}
    />
    {/* 仅当当前Marker被激活时显示InfoWindow */}
    {activeMarkerId === (hotel.id || i) && (
      <InfoWindowF
        position={{ lat: hotel.lat, lng: hotel.lng }}
        onCloseClick={() => setActiveMarkerId(null)}
      >
        <div style={divStyle}>
          <h1>{hotel.name}</h1>
          <img style={{width: "200px", height: "100px"}} src={hotel.img} alt={hotel.name} />
          <Typography>
            Gecelik: {hotel.price}TL - {personCount} kişi: {hotel.price * personCount}TL
          </Typography>
        </div>
      </InfoWindowF>
    )}
  </React.Fragment>
))}

关键修改说明

  • 用唯一标识(ID/索引)替代全局布尔值,精准控制单个InfoWindow的显示/隐藏
  • Marker保持常驻显示,符合地图交互的常规逻辑
  • 添加onMouseOut事件,鼠标离开Marker时自动关闭对应窗口
  • 给InfoWindow增加onCloseClick事件,支持点击关闭按钮手动关闭窗口

内容的提问来源于stack exchange,提问作者mertk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:17:26