Flutter使用google_maps_flutter绘制路线出现额外直达直线问题
问题原因
你出现多余直达直线的核心原因是路线坐标列表没有清空:
polylineCoordinates是全局状态变量,每次请求新路线时,旧的路线坐标还残留在列表中- 新请求的路线坐标会被追加到旧列表末尾,列表中两个不连续的路线点就会被自动连成直线,也就是你看到的A点到B点的直达线
- 如果请求路线接口报错返回空坐标,也可能出现只有起止点被保留、连成直线的情况
修复步骤
1. 每次请求路线前清空坐标列表
修改_getPolyline方法,请求前先清空旧坐标,同时增加接口请求状态校验:
_getPolyline(pickupAddress) async { // 清空残留的旧路线坐标 polylineCoordinates.clear(); PolylineResult result = await polylinePoints.getRouteBetweenCoordinates( mapKey, PointLatLng(_originLatitude, _originLongitude), PointLatLng(_destLatitude, _destLongitude), travelMode: TravelMode.driving, ); // 仅当路线请求成功且返回坐标不为空时再处理 if (result.status == 'OK' && result.points.isNotEmpty) { for (var point in result.points) { polylineCoordinates.add(LatLng(point.latitude, point.longitude)); } } _addPolyLine(); }
2. (可选)每次初始化标记前清空旧数据
如果存在多次搜索切换订单的场景,可以在_initMarkers方法开头清空旧的标记和路线,避免残留旧数据:
_initMarkers(data) { // 清空旧标记、旧路线 markers.clear(); polylines.clear(); _originLatitude = double.parse(data[0]['latitude']); _originLongitude = double.parse(data[0]['longitude']); _destLatitude = double.parse(data[1]['latitude']); _destLongitude = double.parse(data[1]['longitude']); // 原有逻辑不变 _addMarker(LatLng(_originLatitude, _originLongitude), "Pickup", BitmapDescriptor.defaultMarker); _addMarker(LatLng(_destLatitude, _destLongitude), "Destination", BitmapDescriptor.defaultMarkerWithHue(118)); _getPolyline(data[0]['formatted_address']); }
内容的提问来源于stack exchange,提问作者Zia
相关产品推荐
相关产品推荐

