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

React项目中@react-google-maps/api@2.19.2加载报错求助

问题排查与解决方案

核心问题分析

  1. 重复加载Google Maps API脚本
    你同时通过useEffect手动创建script标签加载Google Maps脚本,又使用了@react-google-maps/api提供的LoadScript组件,这会导致脚本重复加载,引发API内部冲突,就是你看到的TypeError: h is undefined错误。

  2. Marker组件参数错误
    selectedAddress状态存储的是格式化地址字符串,但Marker的position属性需要传入包含lat和lng的坐标对象,而非地址文本,这会导致标记无法正确渲染。

修正后的代码

import React, { useState } from "react";
import { GoogleMap, LoadScript, Marker } from "@react-google-maps/api";

const MapContainer = () => {
  // 修改state,同时存储地址文本和坐标
  const [selectedLocation, setSelectedLocation] = useState(null);

  const handleMapClick = (event) => {
    const clickedLat = event.latLng.lat();
    const clickedLng = event.latLng.lng();

    const geocoder = new window.google.maps.Geocoder();
    geocoder.geocode(
      { location: { lat: clickedLat, lng: clickedLng } },
      (results, status) => {
        if (status === "OK") {
          if (results[0]) {
            // 同时保存地址和坐标
            setSelectedLocation({
              address: results[0].formatted_address,
              position: { lat: clickedLat, lng: clickedLng }
            });
          } else {
            console.log("No results found");
          }
        } else {
          console.log("Geocoder failed due to: " + status);
        }
      }
    );
  };

  return (
    <div style={{ width: "100%", height: "400px" }}>
      {/* 仅使用LoadScript组件加载API,移除手动加载逻辑 */}
      <LoadScript 
        googleMapsApiKey="MY_API_KEY"
        libraries={["places"]} // 在这里指定需要加载的libraries
      >
        <GoogleMap
          mapContainerStyle={{ width: "100%", height: "100%" }}
          center={{ lat: 53.23, lng: 35.34 }}
          zoom={10}
          onClick={handleMapClick}
        >
          {/* 使用坐标对象作为Marker的position */}
          {selectedLocation && <Marker position={selectedLocation.position} />}
        </GoogleMap>
      </LoadScript>
      {/* 可选:显示选中的地址 */}
      {selectedLocation && (
        <div style={{ marginTop: 10 }}>
          选中地址:{selectedLocation.address}
        </div>
      )}
    </div>
  );
};

export default MapContainer;

关键修改说明

  • 移除了手动加载Google Maps脚本的useEffect逻辑,完全依赖LoadScript组件管理API加载,避免重复加载冲突。
  • 调整selectedLocation状态结构,同时保存地址文本和坐标对象,确保Marker组件能获取到正确的位置参数。
  • 在LoadScript组件中通过libraries属性指定需要加载的places库,无需在脚本URL中手动拼接。

内容的提问来源于stack exchange,提问作者Iman Rh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:53:10