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

本地React+TS项目Google Maps Autocomplete报错排查求助

React+TypeScript+Vite本地开发Google Maps Autocomplete异常调试方案

针对你遇到的本地Vite开发时Google Maps Autocomplete突然失效(线上正常、控制台无报错)的问题,可按以下步骤排查调试:

1. 验证Google Maps Places库加载状态

@googlemaps/react-wrapper的libraries={["places"]}配置可能在热更新后未正确加载Places库。在MyMap组件中添加验证代码:

useEffect(() => {
  console.log("Places library available:", !!window.google?.maps?.places);
}, []);

热更新后查看控制台输出,若为false,则需检查Wrapper的加载逻辑,可尝试临时修改API_KEY触发Wrapper重新渲染,强制加载脚本。

2. 替换DOM查询为React Ref(避免热更新后元素引用失效)

当前用document.getElementById获取输入框的方式在React热更新后可能失效,改为使用React Ref传递:

  • 父组件中添加Ref:
import { useRef } from 'react';

// ...
const inputRef = useRef<HTMLInputElement>(null);

<TextField 
  ref={inputRef}
  required 
  id="location-id" 
  label="Enter address" 
  variant="standard" 
/>

<Wrapper apiKey={API_KEY} render={render} libraries={["places"]}>
  <MyMap 
    coords={coords}
    center={center}
    style={{width: "calc(65vw-5)", height: "calc(70vh)"}}
    setPoint={setCenter}
    inputRef={inputRef} // 传递Ref给MyMap
  />
</Wrapper>
  • MyMap组件中使用Ref初始化Autocomplete:
import { useRef, useEffect } from 'react';

export default function MyMap(props: propsType & {inputRef: React.RefObject<HTMLInputElement>}){
  const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);

  useEffect(() => {
    const input = props.inputRef.current;
    if (!input || !window.google?.maps?.places) return;

    // 初始化Autocomplete
    const autocomplete = new window.google.maps.places.Autocomplete(input, options);
    autocompleteRef.current = autocomplete;

    // 组件卸载/热更新时清理旧实例
    return () => {
      if (autocompleteRef.current) {
        autocompleteRef.current.unbindAll();
        autocompleteRef.current = null;
      }
    };
  }, [props.inputRef]);
}

3. 排查Autocomplete重复初始化冲突

热更新会导致MyMap组件重复渲染,若未清理旧的Autocomplete实例,会导致功能异常。上述代码中已加入清理逻辑,确保每次渲染只存在一个有效实例。

4. 验证本地API密钥的域名限制

登录Google Cloud控制台,检查API密钥的HTTP referrers限制,确认http://localhost:5173(Vite默认端口)已添加到允许列表。线上环境正常不代表本地域名已授权,热更新可能触发更严格的域名校验。

5. 检查Vite环境变量注入正确性

确认本地环境变量API_KEY已正确注入,Vite中需使用import.meta.env.VITE_XXX格式(需在.env文件中定义为VITE_GOOGLE_MAPS_API_KEY=xxx),在Wrapper处添加日志验证:

console.log("Current API_KEY:", API_KEY);

若输出为空或错误值,需检查Vite环境变量配置。

6. 捕获Google Maps隐藏错误

Google Maps的认证或加载错误可能不显示在控制台,添加全局错误监听:

useEffect(() => {
  const handleAuthFailure = () => {
    console.error("Google Maps Auth Failure");
  };
  window.google?.maps?.event.addListener(window, 'gm_authfailure', handleAuthFailure);
  return () => {
    window.google?.maps?.event.removeListener(handleAuthFailure);
  };
}, []);

同时给Wrapper添加错误回调:

<Wrapper 
  apiKey={API_KEY} 
  render={render} 
  libraries={["places"]}
  onLoadError={(error) => console.error("Wrapper Load Error:", error)}
>

7. 检查输入框DOM状态与样式冲突

热更新后输入框可能被意外设置为disabled或隐藏,用开发者工具检查输入框的disabled属性、display样式;同时查看Google Maps自动生成的.pac-container元素是否存在(Autocomplete下拉框容器),若被样式隐藏,需调整CSS优先级。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:45:09