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

React集成Google Map及Geocoder时出现maps未定义类型错误

解决React集成Google地图时的"TypeError: Cannot read property 'maps' of undefined"错误

这个错误的核心原因很明确:你在Google Maps脚本还没完全加载完成的时候就尝试访问google.maps对象了。看你的代码,你直接在组件外部声明了let geocoder = new google.maps.Geocoder();,但react-google-maps的withScriptjs是异步加载Google Maps脚本的,这时候脚本还没加载好,google对象自然是undefined。

下面给你几个可行的修复方案:

方案1:在组件内部延迟初始化Geocoder

把Geocoder的初始化放到组件的生命周期方法里(如果是类组件)或者useEffect钩子中(如果是函数组件),确保只有在Google Maps脚本加载完成后才执行。如果用的是recompose的withHandlers,可以这样写:

import React from 'react';
import { compose, withProps, withHandlers } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from "react-google-maps"
import { MarkerClusterer } from 'react-google-maps/lib/components/addons/MarkerClusterer';
import { connect } from 'react-redux';

const MyMapComponent = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places,geocoding",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap,
  withHandlers({
    initGeocoder: () => () => {
      // 这里google对象已经可用了
      const geocoder = new google.maps.Geocoder();
      // 后续可以调用geocoder.geocode()等方法处理地址解析逻辑
    }
  }),
  connect(mapStateToProps, mapDispatchToProps)
)(({ initGeocoder }) => {
  // 在组件挂载后初始化Geocoder
  React.useEffect(() => {
    initGeocoder();
  }, []);

  return (
    <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
      {/* 你的Marker、InfoWindow等组件 */}
    </GoogleMap>
  );
});

方案2:使用react-google-maps提供的GeoCoder组件

你原来的代码里导入了GeoCoder,其实react-google-maps提供的这个组件已经封装了Geocoder的初始化逻辑,你可以直接在GoogleMap组件内部使用它,不需要手动创建实例:

<GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
  <GeoCoder
    onGeocodeResult={(results) => {
      console.log('地址解析结果:', results);
      // 在这里处理解析后的结果
    }}
  />
  {/* 其他地图组件 */}
</GoogleMap>

额外注意事项

  • 确保你的Google Maps API URL中包含了geocoding库参数(比如&libraries=geocoding),否则Geocoder服务无法被调用。
  • 检查你的API Key是否已经启用了Geocoding API权限,并且没有超出配额限制。

内容的提问来源于stack exchange,提问作者Pranab V V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:54:58