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

React中使用google-map-react加载谷歌地图时出现getChildren未定义错误

解决google-map-react中"Cannot read properties of undefined (reading 'getChildren')"错误

在React项目中使用google-map-react集成谷歌地图时,出现该错误且代码无语法问题,错误指向google_map_markers.js第100行,大概率是库版本兼容或props使用不当导致,和API密钥关系不大(API密钥错误通常表现为地图加载失败、显示"For development purposes only"等提示)。以下是可行的解决方案:

1. 调整google-map-react版本

这个错误常见于版本不兼容的情况,建议切换到稳定版本:

  • 降级到v2.2.0:npm install google-map-react@2.2.0
  • 或升级到最新稳定版:npm update google-map-react

2. 移除不必要的yesIWantToUseGoogleMapApiInternals属性

如果没有实际用到Google Maps API的内部方法,暂时移除该属性。该属性会触发库的内部特殊处理逻辑,若没有对应配套代码,容易引发未定义错误。

3. 确保Marker组件的坐标属性有效

确认传递给子组件的lat和lng是有效的数字类型,避免出现undefined或非数值情况。

修改后的示例代码

import React from 'react'
import GoogleMapReact from 'google-map-react';

const AnyReactComponent = ({ text }) => <div>{text}</div>;

export default function HappeningsWorldMap() {
    const defaultProps = {
        center: {
            lat: 10.99835602,
            lng: 77.01502627
        },
        zoom: 11
    };

    const handleApiLoaded = (map, maps) => {
        // 如需使用API内部方法,在此添加逻辑
    };

    return (
        <div className='w-6/12 h-96 mx-2 shadow-xl rounded-xl bg-white flex items-start justify-start flex-col'>
            <p className='text-xl font-semibold px-4 py-2'>Happening Locations</p>
            <div className='w-full h-full items-center justify-center'>
                <GoogleMapReact
                    bootstrapURLKeys={{ key: "你的谷歌地图API密钥" }}
                    defaultCenter={defaultProps.center}
                    defaultZoom={defaultProps.zoom}
                    onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
                >
                    <AnyReactComponent
                        lat={59.955413}
                        lng={30.337844}
                        text="My Marker"
                    />
                </GoogleMapReact>
            </div>
        </div>
    )
}

若确实需要使用API内部功能,确保在handleApiLoaded中正确处理map和maps对象,同时使用兼容的库版本即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:47:43