Flutter集成Google Maps失败:无法获取路线并报REQUEST_DENIED错误
解决Flutter订单追踪页面REQUEST_DENIED异常
控制台抛出的REQUEST_DENIED异常是Google Maps API请求被拒绝导致的,以下是针对性的解决步骤:
核心排查点(API相关)
确认API密钥有效性
检查Google Cloud控制台中的API密钥是否正确,有没有输入错误,同时确保密钥处于启用状态(未被禁用)。启用必要的API服务
flutter_polyline_points插件依赖Directions API获取路线,必须在Google Cloud控制台中启用该服务;另外Google Maps组件需要启用Maps SDK for Android和Maps SDK for iOS。
操作路径:Google Cloud控制台 → API和服务 → 库 → 搜索对应API并点击启用。检查API密钥限制设置
如果密钥设置了应用限制(如Android包名、iOS Bundle ID),要确保和Flutter应用的配置完全一致:- Android包名查看
android/app/src/main/AndroidManifest.xml中的package属性 - iOS Bundle ID查看
ios/Runner/Info.plist中的CFBundleIdentifier
测试阶段可以暂时取消限制,验证请求是否正常,上线后再配置严格限制。
- Android包名查看
代码优化建议
- 修复拼写错误:
getCurrentLocaiton改为getCurrentLocation,避免后续定位逻辑出错。 - 添加异常捕获:在
getPolyPoints方法中增加try-catch,避免未处理异常导致应用崩溃:Future<void> getPolyPoints() async { try { PolylinePoints polylinePoints = PolylinePoints(); PolylineResult result = await polylinePoints.getRouteBetweenCoordinates( google_api_key, PointLatLng(sourceLocation.latitude, sourceLocation.longitude), PointLatLng(destination.latitude, destination.longitude), ); if (result.points.isNotEmpty) { polylineCoordinates.clear(); result.points.forEach((PointLatLng point) { polylineCoordinates.add(LatLng(point.latitude, point.longitude)); }); setState(() {}); } else { print("未获取到有效路线点"); } } catch (e) { print("路线获取失败:$e"); } } - 优化地图初始化逻辑:
getCurrentLocation是异步操作,可能导致地图加载时currentLocation仍为null,建议设置默认初始位置为sourceLocation:initialCameraPosition: CameraPosition( target: currentLocation != null ? LatLng(currentLocation!.latitude!, currentLocation!.longitude!) : sourceLocation, zoom: 13.5 ),
内容的提问来源于stack exchange,提问作者Yunus Emre Çakmak
相关产品推荐
相关产品推荐

