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

React+Google Map:map.panTo返回中心无动画及定位问题求助

问题2:获取当前位置作为地图中心

实现步骤:

  1. 将固定的center常量改为React状态,支持动态更新
  2. 使用浏览器原生navigator.geolocationAPI获取当前位置
  3. 组件挂载时触发定位请求,成功后更新地图中心

修改代码:

  1. 替换center定义为状态:
// 预设默认坐标,获取位置后自动更新
const [center, setCenter] = useState({ lat: -1.1797562, lng: 36.9064927 });
  1. 添加useEffect钩子处理定位逻辑:
useEffect(() => {
  if (!navigator.geolocation) {
    toast.error("您的浏览器不支持地理定位功能");
    return;
  }

  navigator.geolocation.getCurrentPosition(
    (position) => {
      setCenter({
        lat: position.coords.latitude,
        lng: position.coords.longitude
      });
    },
    (error) => {
      console.error("定位失败:", error);
      switch(error.code) {
        case error.PERMISSION_DENIED:
          toast.error("您拒绝了位置权限请求");
          break;
        case error.POSITION_UNAVAILABLE:
          toast.error("无法获取当前位置");
          break;
        case error.TIMEOUT:
          toast.error("定位请求超时");
          break;
      }
    }
  );
}, []);
  1. 确保GoogleMap组件绑定状态(原代码已满足,无需额外修改):
<GoogleMap
  center={center}
  zoom={18}
  mapContainerStyle={{ width: '100%', height: '100%' }}
  options={{
    zoomControl: false,
    streetViewControl: false,
    mapTypeControl: false,
    fullscreenControl: false,
    mapTypeId: "satellite"
  }}
  onLoad={map => setMap(map)}
>
  <Marker position={center} />
</GoogleMap>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:10:56