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(获取用户位置可能需要)
二、代码细节修复
- 替换无效API密钥:代码中
findPlaces方法里的const key = 'wxrhaENo';是测试用无效密钥,替换为你从Google Cloud获取的真实密钥。 - 优化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; }
- 修复MarkerId兼容性问题:
place['reference']字段已被新版Places API弃用,Web端建议使用place['place_id']作为Marker的唯一标识:
markerId: MarkerId(place['place_id']),
三、验证配置
完成上述操作后,执行flutter run -d chrome启动Web应用,检查:
- 地图是否正常加载显示
- 点击右上角地图图标,是否能加载并显示附近餐厅的标记
内容的提问来源于stack exchange,提问作者user3523406
相关产品推荐
相关产品推荐

