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

React中如何修改Google Maps API的InfoWindow属性?

解决@react-google-maps/api中InfoWindow选项不生效的问题

问题分析

你遇到的问题主要有两个核心原因:

  1. Marker未绑定触发逻辑:selectedMarker初始值为null,且没有给Marker添加点击事件来更新这个状态,导致InfoWindow从未被渲染,设置的选项自然无法生效。
  2. 样式优先级限制:即便InfoWindow能渲染,直接通过options设置backgroundColor可能被Google Maps内置样式或组件默认样式覆盖,需要通过自定义内容或CSS来调整。

解决方案

步骤1:给Marker添加点击事件,触发InfoWindow显示

修改Marker组件,添加onClick事件来更新selectedMarker状态:

{currentPosition && (
  <Marker 
    position={currentPosition} 
    onClick={() => setSelectedMarker({ position: currentPosition })} 
  />
)}

步骤2:自定义InfoWindow样式(两种可选方式)

方式一:自定义内容容器(推荐,完全可控)

直接在InfoWindow内部传入带样式的自定义内容,彻底控制UI表现:

{selectedMarker && (
  <InfoWindow
    position={selectedMarker.position}
    onCloseClick={() => setSelectedMarker(null)}
  >
    <div style={{ 
      backgroundColor: 'purple', 
      padding: '10px', 
      borderRadius: '4px',
      color: '#fff',
      minWidth: '150px'
    }}>
      这里是自定义窗口内容
    </div>
  </InfoWindow>
)}
方式二:通过options+CSS覆盖内置样式

如果坚持使用options设置,需要搭配CSS覆盖Google Maps的默认样式:

  1. 正确传递options参数:
const infoWindowOptions = {
  backgroundColor: 'purple'
};

// 在InfoWindow组件中使用
<InfoWindow
  options={infoWindowOptions}
  position={selectedMarker.position}
  onCloseClick={() => setSelectedMarker(null)}
>
  <div style={{ color: '#fff', padding: '8px' }}>
    窗口内容
  </div>
</InfoWindow>
  1. 在全局CSS文件中添加覆盖样式:
/* 覆盖Google Maps InfoWindow的内部容器背景色 */
.gm-style .gm-style-iw-d {
  background-color: purple !important;
}

修改后的完整代码

import React, { useState, useEffect } from "react";
import {
  GoogleMap,
  InfoWindow,
  Marker,
  LoadScript,
} from "@react-google-maps/api";

function Map() {
  const apiKey = process.env.REACT_APP_GOOGLE_API_KEY;
  const [currentPosition, setCurrentPosition] = useState(null);
  const [selectedMarker, setSelectedMarker] = useState(null);

  const containerStyle = {
    position: "absolute",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%",
  };

  const success = (position) => {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    setCurrentPosition({ lat: latitude, lng: longitude });
  };

  const error = () => {
    console.log("Unable to retrieve your location");
  };

  const getCurrentLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success, error);
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  };

  useEffect(() => {
    getCurrentLocation();
  }, []);

  return (
    <LoadScript googleMapsApiKey={apiKey}>
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={currentPosition}
        zoom={13}
      >
        {currentPosition && (
          <Marker 
            position={currentPosition} 
            onClick={() => setSelectedMarker({ position: currentPosition })} 
          />
        )}
        {selectedMarker && (
          <InfoWindow
            position={selectedMarker.position}
            onCloseClick={() => setSelectedMarker(null)}
          >
            <div style={{ 
              backgroundColor: 'purple', 
              padding: '10px', 
              borderRadius: '4px',
              color: '#fff',
              minWidth: '150px'
            }}>
              当前位置信息
            </div>
          </InfoWindow>
        )}
      </GoogleMap>
    </LoadScript>
  );
}

export default Map;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:53:17