google_maps_flutter: ^0.5.30
flutter_polyline_points: ^0.2.2
确保你使用了 .then() 函数,因为 setPolyline() 是异步函数并且有 await 关键字。
使用这些依赖项
class ShowMap extends StatefulWidget {
ShowMap({Key key}) : super(key: key);
@override
_ShowMapState createState() => _ShowMapState();
}
class _ShowMapState extends State<ShowMap> {
GoogleMapController _googleMapController;
Set<Polyline> _polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = "YOUR_API_KEY_HERE";
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ColorUtils.bluePrimary,
appBar: AppBar(
// automaticallyImplyLeading: false,
backgroundColor: ColorUtils.greenPrimary,
title: Center(
child: Column(
children: [
Text(
'Delivery Accepted! ',
style: TextStyle(fontSize: 18.0, letterSpacing: -0.3333),
),
],
),
),
),
body: Column(
children: [
Expanded(
flex: 5,
child: Center(
child: Container(
margin: EdgeInsets.only(top: 10),
decoration: BoxDecoration(
// color: Colors.white,
),
width: MediaQuery.of(context).size.width - 10,
height: MediaQuery.of(context).size.height * 0.5,
child: GoogleMap(
cameraTargetBounds: CameraTargetBounds.unbounded,
initialCameraPosition: _initialPosition,
onMapCreated: _onMapCreated,
tiltGesturesEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
// trafficEnabled: true,
polylines: _polylines),
),
),
),
),
],
),
);
}
static final CameraPosition _initialPosition = CameraPosition(
// bearing: 192.8334901395799,
target: LatLng(31.5204, 74.3587),
zoom: 12);
void _onMapCreated(GoogleMapController controller) async {
setState(() {
_googleMapController = controller;
setPolylines().then((_) => _setMapFitToTour(_polylines));
});
}
void _setMapFitToTour(Set<Polyline> p) {
double minLat = p.first.points.first.latitude;
double minLong = p.first.points.first.longitude;
double maxLat = p.first.points.first.latitude;
double maxLong = p.first.points.first.longitude;
p.forEach((poly) {
poly.points.forEach((point) {
if (point.latitude < minLat) minLat = point.latitude;
if (point.latitude > maxLat) maxLat = point.latitude;
if (point.longitude < minLong) minLong = point.longitude;
if (point.longitude > maxLong) maxLong = point.longitude;
});
});
_googleMapController.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(minLat, minLong),
northeast: LatLng(maxLat, maxLong)),
20));
}
setPolylines() async {
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
googleAPIKey,
PointLatLng(31.5204, 74.3587),
PointLatLng(31.4504, 74.1350),
);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
} else {
print("--address not found ---");
}
setState(() {
Polyline polyline = Polyline(
polylineId: PolylineId("poly"),
color: Color.fromARGB(255, 40, 122, 198),
width: 5,
points: polylineCoordinates);
_polylines.add(polyline);
});
}
}