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

React项目中Google Maps Advanced Markers启用失败求助

Google Maps Advanced Markers 配置问题及解决思路

我在React项目中尝试集成Google Maps Advanced Markers,但功能无法正常工作。我怀疑问题出在附图所示的设置上,想知道如何将该设置改为true;如果这个问题始终无法解决,考虑改用Mapbox API。


项目代码

const mapOptions = {
  madId: process.env.NEXT_PUBLIC_MAP_ID, // 注意此处存在拼写错误
  center: { lat: 43.66, lng: -79.39 },
  zoom: 10,
  disableDefaultUI: true,
}

function MyMap() {
  const [ map, setMap ] = useState();
  const ref = useRef();

  useEffect(() => {
    setMap(new google.maps.Map(ref.current, mapOptions))
  }, [])
  return (
    <>
      <div ref={ref} id="map"/>
      {map && <City map={map} />}
    </>
  )
}

const cityData = {
  A: {
    name: "Toronto",
    position: { lat: 43.66, lng: -79.39  }
  },
  B: {
    name: "Amsterdam",
    position: { lat: 53.66, lng: -79.39 }
  }
}

function City({map}) {
  const [ data, setData ] = useState(cityData);

  return (
    <>
      {Object.entries(data).map(([key, city]) => (
        <Marker key={key} map={map} position={city.position}>
          <div className="marker">
            <h2>{city.name}</h2>
          </div>
        </Marker>
      ))}
    </>
  )
}

function Marker({map, children, position}) {
  const markerRef = useRef();
  const rootRef = useRef();
  
  useEffect(() => {
    if (!rootRef.current) {
      const container = document.createElement("div");
      rootRef.current = createRoot(container);
      
      markerRef.current = new google.maps.marker.AdvancedMarkerView({
        position,
        content: container,
      });
    }
  }, []);

  useEffect(() => {
    rootRef.current.render(children)
    markerRef.current.position = position;
    console.log(markerRef.current.map = map);
  }, [map, position, children])
}

渲染代码

<Wrapper apiKey={process.env.REACT_APP_GOOGLE_API_KEY} version="beta" libraries={["marker"]}>
  <MyMap />
</Wrapper>

参考了Google官方视频教程内容。


解决设置为true的方法

你提到的设置是Google Cloud控制台中Maps JavaScript API的Advanced Markers功能开关,开启步骤如下:

  • 登录Google Cloud控制台,进入你的项目
  • 点击左侧菜单「API和服务」→「库」
  • 搜索并找到「Maps JavaScript API」,确认已启用
  • 进入该API的详情页,切换到「功能」标签
  • 找到「Advanced Markers」选项,将其状态切换为启用(即设置为true)

代码中的潜在问题修正

除了设置问题,你的代码还有几处需要调整:

  1. mapOptions中的madId是拼写错误,应改为mapId
  2. MyMap组件的useEffect需加入mapOptions作为依赖项,否则环境变量更新时地图不会重新初始化:
    useEffect(() => {
      setMap(new google.maps.Map(ref.current, mapOptions))
    }, [mapOptions])
    
  3. Marker组件中,设置地图的方式应使用setMap方法,而非直接赋值:
    // 替换原console.log行
    markerRef.current.setMap(map);
    

替代方案:改用Mapbox API

如果上述方法仍无法解决问题,可以尝试使用Mapbox GL JS,以下是React中的基础实现示例:

  1. 先安装依赖:
npm install mapbox-gl @types/mapbox-gl
  1. 基础组件代码:
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { useRef, useEffect } from 'react';

mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_API_KEY;

function MapboxMap() {
  const mapContainerRef = useRef(null);

  useEffect(() => {
    // 初始化地图
    const map = new mapboxgl.Map({
      container: mapContainerRef.current,
      style: 'mapbox://styles/mapbox/streets-v12',
      center: [-79.39, 43.66],
      zoom: 10,
    });

    // 添加自定义标记
    Object.entries(cityData).forEach(([key, city]) => {
      const el = document.createElement('div');
      el.className = 'marker';
      el.innerHTML = `<h2>${city.name}</h2>`;

      new mapboxgl.Marker(el)
        .setLngLat([city.position.lng, city.position.lat])
        .addTo(map);
    });

    // 清理函数
    return () => map.remove();
  }, []);

  return <div ref={mapContainerRef} style={{ width: '100%', height: '400px' }} />;
}

const cityData = {
  A: {
    name: "Toronto",
    position: { lat: 43.66, lng: -79.39  }
  },
  B: {
    name: "Amsterdam",
    position: { lat: 52.3676, lng: 4.9041 } // 修正阿姆斯特丹坐标
  }
};

内容的提问来源于stack exchange,提问作者Max de Ruiter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:57:52