Flutter中getLocation()静态访问错误及Polyline不显示问题
问题解决方案
1. 解决getLocation()静态访问错误
错误原因:getLocation()是Location类的实例方法,直接用类名Location调用属于静态访问实例方法,因此触发报错。
修复步骤:
- 使用创建的
location实例调用getLocation(),而非类名。 - 补充位置权限请求逻辑,否则无法获取位置数据,页面会一直显示"Loading"。
修改后的getCurrentLocation()方法:
void getCurrentLocation() async { Location location = Location(); // 先检查并请求位置服务权限 bool serviceEnabled; PermissionStatus permissionGranted; serviceEnabled = await location.serviceEnabled(); if (!serviceEnabled) { serviceEnabled = await location.requestService(); if (!serviceEnabled) { return; } } permissionGranted = await location.hasPermission(); if (permissionGranted == PermissionStatus.denied) { permissionGranted = await location.requestPermission(); if (permissionGranted != PermissionStatus.granted) { return; } } // 获取当前位置并更新状态 location.getLocation().then( (locationData) { setState(() { currentLocation = locationData; }); }, ); }
2. 解决Polyline无法显示的问题
以下是常见原因及对应修复方案:
原因1:Google API Key未启用Directions API
flutter_polyline_points依赖Google Directions API获取路线坐标,需在Google Cloud控制台启用该API,并确保API Key绑定了正确的项目。
原因2:地图初始视角未覆盖路线区域
当前地图初始相机位置为用户当前位置,若路线不在视野范围内,会导致Polyline不可见。可调整初始相机位置至包含起点和终点的区域:
// 替换原initialCameraPosition代码 initialCameraPosition: CameraPosition( target: LatLng( (sourcelocation.latitude + destination.latitude) / 2, (sourcelocation.longitude + destination.longitude) / 2, ), zoom: 14.5, ),
原因3:Polyline数据未正确填充或更新
- 添加日志验证路线点是否成功获取:
void getPolyPoints() async { PolylinePoints polylinePoints = PolylinePoints(); PolylineResult result = await polylinePoints.getRouteBetweenCoordinates( googleApiKey, PointLatLng(sourcelocation.latitude, sourcelocation.longitude), PointLatLng(destination.latitude, destination.longitude), ); // 打印结果验证是否获取到路线点 print("路线点数量:${result.points.length}"); print("API返回状态:${result.status}"); if (result.points.isNotEmpty) { polylineCoordinates.clear(); // 清空旧数据避免重复 result.points.forEach( (PointLatLng point) => polylineCoordinates.add( LatLng(point.latitude, point.longitude), ), ); setState(() {}); } }
- 确保
googleApiKey替换为自身的有效密钥,且密钥未被限制使用范围。
内容的提问来源于stack exchange,提问作者user13534191
相关产品推荐
相关产品推荐

