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

如何替换GoogleApiWrapper,直接在HTML标签中配置谷歌地图API密钥?

改用HTML直接引入谷歌地图API替代google-maps-react的GoogleApiWrapper

步骤1:在HTML中引入谷歌地图API

找到项目根目录下的public/index.html,在<head>标签内添加谷歌地图API脚本,替换成你的有效API密钥:

<script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥"></script>

如果需要用到地点搜索等额外功能,可以追加&libraries=places参数

步骤2:重构MapContainer组件(maps.js)

删掉原有的google-maps-react依赖代码,改用原生谷歌地图API初始化地图:

import React, { useEffect, useRef } from 'react';

const MapContainer = () => {
  const mapContainerRef = useRef(null);

  useEffect(() => {
    // 确保谷歌地图全局对象已加载
    if (!window.google) return;

    // 初始化地图实例
    const map = new window.google.maps.Map(mapContainerRef.current, {
      center: { lat: 39.9042, lng: 116.4074 }, // 默认北京坐标,按需修改
      zoom: 10, // 初始缩放级别,按需调整
    });

    // 示例:添加地图标记(可选)
    new window.google.maps.Marker({
      position: { lat: 39.9042, lng: 116.4074 },
      map: map,
      title: '我的位置',
    });

    // 组件卸载时清理地图,避免内存泄漏
    return () => map.setMap(null);
  }, []);

  // 必须给容器设置明确的宽高,否则地图无法显示
  return <div ref={mapContainerRef} style={{ width: '100%', height: '500px' }} />;
};

export default MapContainer;

步骤3:修改App.js直接渲染MapContainer

移除GoogleApiWrapper包装逻辑,直接导入并使用组件:

import React from 'react';
import MapContainer from './maps';

function App() {
  return (
    <div className="App">
      <MapContainer />
    </div>
  );
}

export default App;

关键注意点

  • 确认你的API密钥已经在谷歌云控制台开启了Maps JavaScript API权限,否则地图会加载失败
  • 地图容器必须设置宽高(行内样式或CSS类均可),这是地图显示的必要条件
  • 若不再需要google-maps-react库,可执行npm uninstall google-maps-react清理依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:05:32