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

React Google Maps集成StandaloneSearchBox后持续加载异常问题

问题解决:React Google地图StandaloneSearchBox加载异常

核心问题分析

  • 函数组件错误使用this:函数组件无实例this,无法通过this.searchBox保存引用,导致逻辑阻塞
  • 缺失Places API库加载:StandaloneSearchBox依赖Google Maps Places API,必须显式声明加载该库
  • 自定义ScriptLoaded导入错误:不应从本地../api/docs导入,需使用@react-google-maps/api自带的LoadScript
  • React属性语法错误:HTML的class需改为className,input标签属性写法不符合React规范

修复步骤

  1. 用useRef替代this:通过React的useRef钩子保存搜索框引用,解决函数组件无this的问题
  2. 添加Places库加载参数:在LoadScript组件中加入libraries={['places']},确保加载所需API
  3. 修正React属性写法:将所有class替换为className,完善input标签的type属性
  4. 移除错误导入:删除自定义ScriptLoaded导入,仅保留@react-google-maps/api的官方组件

修正后的完整代码

import { useState, useEffect, useRef } from 'react'
import { GoogleMap, StandaloneSearchBox, LoadScript } from '@react-google-maps/api';

const initialState = {
  company: '',
  email: '',
  password: '',
  isMember: true,
}

const Register = () => {
  const mapContainerStyle = {
    height: "400px",
    width: "800px"
  }
  
  const center = {
    lat: -3.745,
    lng: -38.523
  };

  const [values, setValues] = useState(initialState)
  const searchBoxRef = useRef(null);

  const handleChange = (e) => {
    console.log(e.target)
  }

  const onSubmit = (e) => {
    e.preventDefault()
    console.log(e.target)
  }

  const handleLoad = (ref) => {
    searchBoxRef.current = ref;
  };

  const handlePlacesChanged = () => {
    if (searchBoxRef.current) {
      const places = searchBoxRef.current.getPlaces();
      console.log(places);
      // 可扩展逻辑:根据搜索结果更新地图中心或添加Marker
    }
  };

  return (
    <div className="page-template-default page page-id-13">
      <header className="site-header">
        <div className="container">
          <h1 className="school-logo-text float-left">
            <a href="/landing"><strong>Direct</strong> Connection</a>
          </h1>
          <div className="site-header__util"></div>
        </div>
      </header>

      <div className="page-banner">
        <div className="page-banner__bg-image" style={{ backgroundImage: "url('connection.jpg')" }}></div>
        <div className="page-banner__content container container--narrow">
          <h1 className="page-banner__title">Register</h1>
          <div className="page-banner__intro">
            <p></p>
          </div>
        </div>
      </div>

      <div className="container container--narrow page-section">
        <h2 className="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
        
        <label className="header">Profile Photo:</label>
        <input id="image" type="file" name="profile_photo" placeholder="Photo" required capture />
        
        <label className="company-name">Company Name</label>
        <div className="company-input">
          <input type="text" className="headline headline--input" placeholder="Enter Company" />
        </div>
        
        <label className="company-email">Email</label>
        <div className="email-input">
          <input type="email" className="headline headline--input" placeholder="Enter Email" />
        </div>

        <label className="company-map">Map</label>   
        <div className="map-input">
          <LoadScript
            googleMapsApiKey='API_HERE'
            libraries={['places']}
          >
            <GoogleMap
              id="map"
              mapContainerStyle={mapContainerStyle}
              center={center}
              zoom={10}
            >
              <StandaloneSearchBox
                onLoad={handleLoad}
                onPlacesChanged={handlePlacesChanged}
              >
                <input
                  type="text"
                  placeholder="Search for your location"
                  style={{
                    boxSizing: `border-box`,
                    border: `1px solid transparent`,
                    width: `240px`,
                    height: `32px`,
                    padding: `0 12px`,
                    borderRadius: `3px`,
                    boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
                    fontSize: `14px`,
                    outline: `none`,
                    textOverflow: `ellipses`,
                    position: "absolute",
                    left: "50%",
                    marginLeft: "-120px",
                    marginTop: "10px"
                  }}
                />
              </StandaloneSearchBox>
            </GoogleMap>
          </LoadScript>
        </div>  
      </div>
      
      <footer className="site-footer">
        <div className="site-footer__inner container container--narrow">
          <div className="group">
            <div className="site-footer__col-one">
              <h1 className="school-logo-text school-logo-text--alt-color">
                <a href="/landing"><strong>Direct</strong> Connection</a>
              </h1>
              <p><a className="site-footer__link" href="index.html">706-263-0175</a></p>
            </div>
          </div>
        </div>
      </footer>
    </div>
  )
}

export default Register

额外优化方向

  • 在handlePlacesChanged中添加逻辑:将搜索到的地点坐标设为地图中心,并添加Marker标记企业位置
  • 绑定表单输入到values状态,实现双向数据绑定
  • 确认Google Maps API密钥已启用Places API权限,避免权限导致的加载失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:40:25