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

Google Maps Marker被InfoWindow遮挡,如何调整其至Marker上方?

解决Google Maps API中InfoWindow遮挡Marker的问题

问题原因

你当前使用的anchor属性并不是InfoWindow组件的有效配置项(该属性属于Marker),导致无法正确调整InfoWindow的位置,进而遮挡Marker。此外,直接用CSS调整Google Maps的InfoWindow通常无效,因为它是独立于React组件树的DOM元素,受Maps API控制。

解决方案

将InfoWindow的位置偏移方式改为API支持的pixelOffset属性,通过设置像素偏移让InfoWindow定位到Marker上方:

修改后的完整代码

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

function Map() {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
  });

  const location = { lat: -33.81724, lng: 150.99908 };
  const [selectedMarker, setSelectedMarker] = useState(null);

  if (!isLoaded) return <div>Loading...</div>;

  const handleMarkerClick = (marker) => {
    setSelectedMarker(marker);
  };

  // 创建像素偏移对象,让InfoWindow向上偏移40px
  const infoWindowOffset = new window.google.maps.Size(0, -40);

  return (
    <GoogleMap
      zoom={20}
      center={{ lat: location.lat, lng: location.lng }}
      mapContainerStyle={{
        position: "relative",
        top: 50,
        right: 290,
        width: "230%",
        height: "30vh",
      }}
    >
      <Marker position={location} onClick={() => handleMarkerClick(location)} />
      {selectedMarker && (
        <InfoWindow
          position={selectedMarker}
          pixelOffset={infoWindowOffset}
          onCloseClick={() => setSelectedMarker(null)}
        >
          <div>
            <h3>ABAD & VILLANUEVA SOLICITOR'S</h3>
          </div>
        </InfoWindow>
      )}
    </GoogleMap>
  );
}

export default Map;

关键修改点

  • 移除无效的anchor属性,替换为pixelOffset,通过google.maps.Size定义偏移量(x轴0,y轴-40表示向上偏移40像素)
  • 确保偏移量是Maps API提供的Size对象,而非普通对象,这样才能被正确识别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:13:18