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

Next13+TypeScript集成@react-google-maps/api地图不显示且无控制台错误

Next13 + TypeScript 谷歌地图显示空白问题排查与解决

一、检查地图容器高度

你的GoogleMap组件设置了mapContainerStyle={{width: '100%', height: '100%'}},但如果父元素未设置明确高度,100%高度会失效,导致地图容器实际高度为0,视觉上呈现空白。

解决方法:
给Ground组件的根容器设置明确高度,比如:

// Ground组件的return部分修改
return (
  <div style={{ width: '100vw', height: '100vh' }}>
    <GoogleMap
      zoom={8}
      center={center}
      options={options}
      onLoad={onLoad}
      mapContainerStyle={{
        width: '100%',
        height: '100%',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
    </GoogleMap>
  </div>
);

也可以在全局CSS中给html, body设置height: 100%,确保所有父级容器有高度支撑。

二、验证用户位置是否正确获取

如果getUserLocation未成功获取位置,baseLocation会保持undefined,导致地图center参数为空,无法加载地图内容。

排查与修复:

  1. 在位置获取函数中添加日志,确认获取结果:
async function fetchLocationInformation() {
  try {
    const userLocation = await getUserLocation();
    console.log('获取到的位置:', userLocation);
    if (userLocation) {
      setBaseLocation(userLocation);
    } else {
      console.log('未获取到用户位置');
    }
  } catch (error) {
    console.error('获取位置失败:', error);
  }
}
  1. 检查useLocation的getUserLocation实现,确保正确调用浏览器Geolocation API,示例参考:
export function useLocation() {
  const [loading, setLoading] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState<string | null>(null);

  const getUserLocation = async (): Promise<ICoordinates | null> => {
    setLoading(true);
    setErrorMsg(null);
    return new Promise((resolve, reject) => {
      if (!navigator.geolocation) {
        setErrorMsg('浏览器不支持地理定位');
        setLoading(false);
        reject(new Error('浏览器不支持地理定位'));
        return;
      }
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLoading(false);
          resolve({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          });
        },
        (error) => {
          setLoading(false);
          const msg = error.code === error.PERMISSION_DENIED ? '用户拒绝了位置权限' : '获取位置失败';
          setErrorMsg(msg);
          reject(new Error(msg));
        }
      );
    });
  };

  return { getUserLocation, errorMsg, loading };
}
  1. 若位置获取失败,可设置默认中心点兜底:
const center = React.useMemo<LatLngLiteral>(
  () => baseLocation ? { lat: baseLocation.latitude, lng: baseLocation.longitude } : { lat: 39.9042, lng: 116.4074 }, // 默认北京坐标
  [baseLocation]
);

三、检查Google Maps API Key配置

  1. 确认API Key已启用Maps JavaScript API:登录Google Cloud控制台,找到对应项目,在API库中搜索并启用该API。
  2. 检查API Key的权限限制:如果设置了HTTP限制,需将本地开发地址(如http://localhost:3000)或生产域名加入允许列表。
  3. 验证API Key有效性:直接访问https://maps.googleapis.com/maps/api/js?key=你的API_KEY,若返回正常JS文件则Key有效,若返回错误提示则需重新配置。

四、检查Map ID有效性

你使用的mapId是教程示例ID,可能未关联到你的Google Cloud项目,导致地图样式加载失败。

解决方法:

  • 暂时移除mapId配置,使用默认地图样式:
const options = React.useMemo<MapOptions>(
  () => ({
    clickableIcons: true,
    scrollwheel: true,
    // 移除mapId配置
  }),
  [colorScheme]
);
  • 或在Google Cloud控制台创建自己的Map ID并关联项目,替换成自定义ID。

五、确认依赖版本兼容性

确保@react-google-maps/api版本与Next.js 13兼容,建议使用最新稳定版,避免因版本冲突导致渲染异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:27:10