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

google-map-react组件问题:无法设置自定义地图中心坐标

问题:google-map-react无法动态更新地图中心坐标

组件通过调用Google Geocoding API获取指定地址的经纬度,控制台已打印出正确的经纬度值,但地图始终停留在默认坐标(lat: 60, lng: 30),未更新到新坐标。

相关代码

import { AppContainer, Title, Image } from './styledMapApp'; 
import { useEffect, useState } from 'react'; 
import GoogleMapReact from 'google-map-react'; 
import axios from 'axios';

const MapApp = ({ location }: { location?: string }) => {   
  const apiKey = 'mykey';   
  const [latitude, setLatitude] = useState<number>(60);   
  const [longitude, setLongitude] = useState<number>(30);   
  const testingAddress = 'Arrivals Hall, Sydney International Airport, NSW 2020';   
  const encodedAddress = encodeURIComponent(testingAddress);

  const fetchAddress = async () => {
    try {
      const response = await axios.get(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${apiKey}`
      );
      const address = response.data.results[0].geometry.location;
      const currentLatitude = address.lat;
      const currentLongitude = address.lng;

      setLatitude(currentLatitude);
      setLongitude(currentLongitude);
    } catch (error) {
      console.error(error);
    }   
  };

  useEffect(() => {
    fetchAddress();   
  }, []);

  const defaultProps = {
    zoom: 11,   
  };
  console.log(latitude);
  console.log(longitude);

  return (
    <AppContainer>
      <Title>MapApp</Title>
      <div style={{ height: '30vh', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={{ key: apiKey }}
          defaultCenter={{ lat: latitude, lng: longitude }}
          defaultZoom={defaultProps.zoom}
        ></GoogleMapReact>
      </div>
    </AppContainer>   
  }; 
}; 

export default MapApp;

控制台输出

60.      MapApp.tsx:36 
30.      MapApp.tsx:37 
-33.9325244.     MapApp.tsx:36 
151.1793765.     MapApp.tsx:37

原因分析

google-map-react中的defaultCenter是初始化属性,仅在组件首次挂载时生效。当后续通过setLatitude/setLongitude更新state时,defaultCenter不会触发地图重新计算中心坐标,因此地图保持初始的默认值不变。

解决方案

将GoogleMapReact组件的defaultCenter替换为center属性,center支持动态更新,当依赖的state变化时会自动触发地图中心更新:

修改后的地图组件代码片段:

<GoogleMapReact
  bootstrapURLKeys={{ key: apiKey }}
  center={{ lat: latitude, lng: longitude }} // 替换defaultCenter为center
  defaultZoom={defaultProps.zoom}
></GoogleMapReact>

额外优化:可以添加加载状态提示,避免在API请求返回前显示默认坐标的地图:

const [isLoading, setIsLoading] = useState(true);

const fetchAddress = async () => {
  try {
    // ... 原有请求逻辑
    setLatitude(currentLatitude);
    setLongitude(currentLongitude);
  } catch (error) {
    console.error(error);
  } finally {
    setIsLoading(false);
  }
};

// 渲染时
return (
  <AppContainer>
    <Title>MapApp</Title>
    <div style={{ height: '30vh', width: '100%' }}>
      {isLoading ? (
        <div>加载中...</div>
      ) : (
        <GoogleMapReact
          bootstrapURLKeys={{ key: apiKey }}
          center={{ lat: latitude, lng: longitude }}
          defaultZoom={defaultProps.zoom}
        ></GoogleMapReact>
      )}
    </div>
  </AppContainer>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:05:26