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

Flutter Web集成Google Maps API问题:地图仅显示标题不加载

Flutter Web端Google Maps配置指南及问题修复

一、Web端核心配置步骤

  • 打开项目根目录下的web/index.html文件
  • 在<head>标签内添加Google Maps JavaScript API加载脚本,将YOUR_API_KEY替换为你的真实Google Maps API密钥:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

注意:libraries=places必须添加,因为你的代码用到了地点附近搜索功能,缺失会导致搜索逻辑失效。

  • 确保你的API密钥已在Google Cloud控制台启用以下服务:
    • Maps JavaScript API(Web端地图加载必备)
    • Places API(地点搜索功能必备)
    • Geolocation API(获取用户位置可能需要)

二、代码细节修复

  1. 替换无效API密钥:代码中findPlaces方法里的const key = 'wxrhaENo';是测试用无效密钥,替换为你从Google Cloud获取的真实密钥。
  2. 优化Web端位置权限处理:location包在Web端的权限逻辑有差异,建议完善定位失败的 fallback 逻辑:
Future<LatLng> findUserLocation() async {
  Location location = Location();
  LocationData? userLocation;
  PermissionStatus hasPermission = await location.hasPermission();
  bool active = await location.serviceEnabled();

  if (hasPermission == PermissionStatus.granted && active) {
    try {
      userLocation = await location.getLocation();
      userPosition = LatLng(userLocation.latitude!, userLocation.longitude!);
    } catch (e) {
      // Web端定位失败时使用默认位置
      userPosition = const LatLng(51.5285582, -0.24167);
    }
  } else {
    // 主动请求权限和定位服务
    hasPermission = await location.requestPermission();
    active = await location.requestService();
    if (hasPermission == PermissionStatus.granted && active) {
      userLocation = await location.getLocation();
      userPosition = LatLng(userLocation.latitude!, userLocation.longitude!);
    } else {
      userPosition = const LatLng(51.5285582, -0.24167);
    }
  }
  return userPosition;
}
  1. 修复MarkerId兼容性问题:place['reference']字段已被新版Places API弃用,Web端建议使用place['place_id']作为Marker的唯一标识:
markerId: MarkerId(place['place_id']),

三、验证配置

完成上述操作后,执行flutter run -d chrome启动Web应用,检查:

  • 地图是否正常加载显示
  • 点击右上角地图图标,是否能加载并显示附近餐厅的标记

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:29:50