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

React新手集成Google Map遇google-maps-react依赖及模块找不到问题求助

问题解决:React 18集成Google Maps的依赖与代码错误

一、依赖树错误原因

google-maps-react 已停止维护,其声明的peer依赖仅支持React ~0.14.8、15.0.0或16.0.0,而你当前项目使用React 18.2.0,版本不匹配导致安装失败,进而出现模块找不到的编译错误。

二、解决方案

1. 替换为兼容React 18的Google Maps包

卸载无效包(未安装成功可跳过),安装维护中的替代包:

npm uninstall google-maps-react
npm install @react-google-maps/api

2. 修正代码中的函数组件错误

你的代码用了函数组件App,但写法是类组件逻辑(this.props、this.state),结合新包API,修正后的代码如下:

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

// 定义地图默认中心坐标(可按需修改)
const defaultCenter = { lat: 37.7749, lng: -122.4194 };

function App() {
  // 用useState管理选中的标记点状态
  const [selectedPlace, setSelectedPlace] = useState(null);

  // 标记点点击事件
  const onMarkerClick = () => {
    setSelectedPlace({ name: 'Current location' });
  };

  // 信息窗口关闭事件
  const onInfoWindowClose = () => {
    setSelectedPlace(null);
  };

  return (
    <div className="App">
      <header className="App-header">
        {/* 加载Google Maps脚本,传入你的API Key */}
        <LoadScript googleMapsApiKey="AIzaSyBwl84ZlMZeFUjUxCQK0MMEh5QL_0SRtfI">
          <GoogleMap
            mapContainerStyle={{ width: '800px', height: '600px' }}
            center={defaultCenter}
            zoom={14}
          >
            {/* 标记点组件 */}
            <Marker
              position={defaultCenter}
              onClick={onMarkerClick}
            />

            {/* 信息窗口,仅选中标记点时显示 */}
            {selectedPlace && (
              <InfoWindow
                position={defaultCenter}
                onCloseClick={onInfoWindowClose}
              >
                <div>
                  <h1>{selectedPlace.name}</h1>
                </div>
              </InfoWindow>
            )}
          </GoogleMap>
        </LoadScript>
      </header>
    </div>
  );
}

export default App;

代码修改说明:

  • 替换导入组件为@react-google-maps/api提供的API
  • 用useState替代类组件的this.state管理状态
  • 用LoadScript组件加载Google Maps脚本,替代原有的GoogleApiWrapper高阶组件
  • 函数组件中直接定义事件处理函数,不再使用this.onXXX写法
  • 给GoogleMap添加mapContainerStyle属性,显式指定地图容器宽高(新包需手动设置)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:31:31