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

首次调用时new google.maps.Polygon未定义,重渲染后正常的问题求助

解决方案:确保Google Maps API加载完成后再执行函数

你的问题核心是首次触发函数时,Google Maps API(包括依赖的geometry库)还未完全加载完毕,导致google.maps.Polygon等API方法未定义;页面重渲染后API已经加载完成,所以函数能正常运行。以下是几种可行的解决方式:

方式1:使用useLoadScript钩子监听API加载状态

@react-google-maps/api提供的useLoadScript钩子可以直接获取API的加载状态,只有当加载完成后才允许执行insidePolygon2函数。

修改代码如下:

import { useLoadScript } from '@react-google-maps/api';

function YourComponent() {
  const libraries = ['places', 'geometry'];
  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: "AIzaSyD6GLBRhQWQ3Kubf7jD4_DqI-bMo5R7d8Y",
    libraries: libraries,
  });

  // 处理加载错误
  if (loadError) return <div>地图加载失败</div>;
  // 未加载完成时禁用函数触发(比如按钮置灰)
  if (!isLoaded) return <div>地图加载中...</div>;

  function insidePolygon2() {
    // 你的函数逻辑保持不变
    const originIndexArray = [];
    const destinationIndexArray = [];
    const indexRouteArray = [];
    const matchedRoutePrices = [];

    polygonCoordinatesFormatted.forEach((polygonCoordinate, i) => {
      let bermudaTriangle = new google.maps.Polygon({ paths: polygonCoordinate });

      if (google.maps.geometry.poly.containsLocation(new google.maps.LatLng(originLat, originLng), bermudaTriangle)) {
        originIndexArray.push(theOgr[i].ogr);
      }

      if (google.maps.geometry.poly.containsLocation(new google.maps.LatLng(destinationLat, destinationLng), bermudaTriangle)) {
        destinationIndexArray.push(theOgr[i].ogr);
      }
    });

    originIndexArray.forEach((origin) => {
      destinationIndexArray.forEach((destination) => {
        const routeIndex = origin + " - " + destination;
        indexRouteArray.push(routeIndex);
      });
    });

    indexRouteArray.forEach((route) => {
      matchedRouteArray.forEach((matchedRoute) => {
        if (route === matchedRoute.route) {
          matchedRoutePrices.push(matchedRoute.price);
        }
      });
    });

    setMaxPrice(Math.max(...matchedRoutePrices))
  }

  // 渲染组件,只有isLoaded为true时才显示可触发函数的元素
  return (
    <button onClick={insidePolygon2}>运行函数</button>
    {/* 其他组件内容 */}
  )
}

方式2:在函数内部添加API就绪检查

如果不想改动组件结构,可以在insidePolygon2函数开头添加检查,确保Google Maps相关API已定义后再执行逻辑:

function insidePolygon2() {
  // 检查核心API是否就绪
  if (!google?.maps?.Polygon || !google?.maps?.geometry?.poly) {
    alert("地图API尚未加载完成,请稍后重试");
    return;
  }

  // 后续原函数逻辑不变
  const originIndexArray = [];
  // ... 剩余代码
}

方式3:利用LoadScript的onLoad回调初始化状态

可以通过LoadScript的onLoad回调设置一个状态,标记API已加载完成,然后在触发函数时判断该状态:

function YourComponent() {
  const [libraries] = useState(['places', 'geometry']);
  const [mapsReady, setMapsReady] = useState(false);

  function handleMapsLoaded() {
    setMapsReady(true);
  }

  function insidePolygon2() {
    if (!mapsReady) {
      console.log("地图未就绪");
      return;
    }
    // 原函数逻辑
  }

  return (
    <LoadScript
      googleMapsApiKey="AIzaSyD6GLBRhQWQ3Kubf7jD4_DqI-bMo5R7d8Y"
      libraries={libraries}
      onLoad={handleMapsLoaded}
    >
      <button onClick={insidePolygon2} disabled={!mapsReady}>运行函数</button>
      {/* 其他组件 */}
    </LoadScript>
  )
}

关键说明

  • 你之前直接取window.google的方式,在API未加载时google可能为undefined,或者其内部的maps属性还未初始化。
  • 必须确保geometry库也加载完成,因为你的函数用到了google.maps.geometry.poly.containsLocation,而libraries数组里已经包含了geometry,所以只要等待加载完成即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:11:13