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

google-maps-react中点击Marker无法弹出InfoWindow求助

问题分析与修复方案

你的代码核心问题在于用全局布尔状态showInfoWindow统一控制所有标记的信息窗口,点击标记时所有窗口会同时触发显示逻辑,但每个标记的信息窗口应该和自身的选中状态绑定,而非全局统一控制。

修复步骤:

  1. 将状态从布尔值改为记录当前选中标记的唯一标识(比如用dreOfficer的email,天然具备唯一性)
  2. 点击标记时切换选中状态:点击已选中的标记则关闭窗口,点击其他标记则切换显示目标
  3. 每个InfoWindow的visible属性仅在当前标记为选中状态时触发显示

修改后的完整代码:

const MapContainer = (props) => {
    const mapStyles = { width: '70%', height: '70%', position: 'relative' };
    // 记录当前选中标记的email,初始为null
    const [selectedMarker, setSelectedMarker] = useState(null);

    return (
        <Map google={props.google} style={mapStyles} zoom={14}>
            {dreInfos.map((dreOfficer, index) => {
                return (
                    <Marker
                        name={dreOfficer.dreOfficer}
                        position={{ lat: dreOfficer.lat, lng: dreOfficer.lng }}
                        key={index}
                        onClick={() => {
                            console.log("Marker Clicked");
                            // 切换选中状态:点击当前选中标记则取消,否则设置为当前标记
                            setSelectedMarker(prev => prev === dreOfficer.email ? null : dreOfficer.email);
                        }}
                    >
                        <InfoWindow
                            key={dreOfficer.email}
                            // 仅当前标记与选中标识匹配时显示
                            visible={selectedMarker === dreOfficer.email}
                        >
                            <div>Dre Officer: {dreOfficer.dreOfficer}</div>
                        </InfoWindow>
                    </Marker>
                )
            })}
        </Map>
    )
};

export default GoogleApiWrapper((props) => ({
    apiKey: props.REACT_APP_GOOGLE_API_KEY
}))(MapContainer)

额外优化建议:

  • 用email作为唯一标识比索引更可靠,避免列表顺序变化导致的状态混乱
  • 若需点击地图空白处关闭信息窗口,可给<Map>添加onClick事件,将selectedMarker设为null

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:13:21