Draw Route Line
This example shows:
-
Draw Route Line
- await navNextBillionMap.drawRoute(routes)
-
Toggle Alternative Routes Visibility
- navNextBillionMap.toggleAlternativeVisibilityWith(value)
-
Toggle Route Duration Symbol Visibility
- navNextBillionMap.toggleDurationSymbolVisibilityWith(value)
![]() | ![]() |
Android snapshot | iOS snapshot |
For all code examples, refer to Flutter Navigation Code Example
DrawRouteLine view source
1import 'dart:math';
2
3import 'package:flutter/material.dart';
4import 'package:nb_maps_flutter/nb_maps_flutter.dart';
5import 'package:nb_navigation_flutter/nb_navigation_flutter.dart';
6
7class DrawRouteLine extends StatefulWidget {
8 static const String title = "Draw Route Line";
9
10
11 DrawRouteLineState createState() => DrawRouteLineState();
12}
13
14class DrawRouteLineState extends State<DrawRouteLine> {
15 NextbillionMapController? controller;
16 List<DirectionsRoute> routes = [];
17 late NavNextBillionMap navNextBillionMap;
18
19 LatLng origin = LatLng( 17.457302037173775, 78.37463792413473);
20 LatLng dest = LatLng(17.466320809357967, 78.3726774987914);
21
22 bool enableAlternativeRoutes = true;
23 bool enableRouteDurationSymbol = true;
24
25 void _onMapCreated(NextbillionMapController controller) {
26 this.controller = controller;
27 }
28
29 void _onStyleLoaded() {
30 if (controller != null) {
31 navNextBillionMap = NavNextBillionMap(controller!);
32 }
33 }
34
35 _onMapClick(Point<double> point, LatLng coordinates) {
36 navNextBillionMap.addRouteSelectedListener(coordinates, (selectedRouteIndex) {
37 if (routes.isNotEmpty && selectedRouteIndex != 0) {
38 var selectedRoute = routes[selectedRouteIndex];
39 routes.removeAt(selectedRouteIndex);
40 routes.insert(0, selectedRoute);
41 setState(() {
42 routes = routes;
43 });
44 navNextBillionMap.drawRoute(routes);
45 }
46 });
47 }
48
49
50 void initState() {
51 super.initState();
52 }
53
54
55 Widget build(BuildContext context) {
56 var screenHeight = MediaQuery.of(context).size.height;
57
58 return Scaffold(
59 appBar: AppBar(
60 title: const Text(DrawRouteLine.title),
61 ),
62 body: SingleChildScrollView(
63 child: Column(
64 children: [
65 Container(
66 constraints: BoxConstraints(maxHeight: screenHeight * 0.6),
67 child: NBMap(
68 onMapCreated: _onMapCreated,
69 initialCameraPosition: CameraPosition(
70 target: LatLng(origin.latitude, origin.longitude),
71 zoom: 13.0,
72 ),
73 onStyleLoadedCallback: _onStyleLoaded,
74 onMapClick: _onMapClick,
75 ),
76 ),
77 _buttonWidget(),
78 _switchButton(),
79 ],
80 ),
81 ),
82 );
83 }
84
85 void _fetchRoute() async {
86 RouteRequestParams requestParams = RouteRequestParams(
87 origin: origin,
88 destination: dest,
89 alternatives: true,
90 mode: ValidModes.car,
91 geometryType: SupportedGeometry.polyline,
92 );
93
94 await NBNavigation.fetchRoute(requestParams, (routes, error) async {
95 if (routes.isNotEmpty) {
96 setState(() {
97 this.routes = routes;
98 });
99 drawRoutes(routes);
100 } else if (error != null) {
101 print("====error====${error}");
102 }
103 });
104 }
105
106 void _startNavigation() {
107 if (routes.isEmpty) return;
108 NavigationLauncherConfig config = NavigationLauncherConfig(route: routes.first, routes: routes);
109 config.locationLayerRenderMode = LocationLayerRenderMode.GPS;
110 config.enableDissolvedRouteLine = false;
111 config.themeMode = NavigationThemeMode.system;
112 config.useCustomNavigationStyle = false;
113 NBNavigation.startNavigation(config);
114 }
115
116 Future<void> drawRoutes(List<DirectionsRoute> routes) async {
117 navNextBillionMap.clearRoute();
118 await navNextBillionMap.drawRoute(routes);
119 }
120
121
122 void dispose() {
123 super.dispose();
124 }
125
126 _buttonWidget() {
127 return Padding(
128 padding: const EdgeInsets.only(left: 8, top: 18.0),
129 child: Row(
130 children: [
131 ElevatedButton(
132 style: ButtonStyle(
133 backgroundColor: MaterialStateProperty.all(Colors.blueAccent),
134 ),
135 onPressed: () {
136 _fetchRoute();
137 },
138 child: const Text("Fetch Route"),
139 ),
140 const Padding(padding: EdgeInsets.only(left: 8)),
141 ElevatedButton(
142 style: ButtonStyle(
143 backgroundColor: MaterialStateProperty.all(routes.isEmpty ? Colors.grey : Colors.blueAccent),
144 enableFeedback: routes.isNotEmpty),
145 onPressed: () {
146 _startNavigation();
147 },
148 child: const Text("Start Navigation"),
149 ),
150 ],
151 ),
152 );
153 }
154
155 _switchButton() {
156 return Padding(
157 padding: const EdgeInsets.all(8.0),
158 child: Column(
159 mainAxisAlignment: MainAxisAlignment.end,
160 crossAxisAlignment: CrossAxisAlignment.start,
161 children: [
162 Row(
163 children: [
164 Text("Display Alternative Route"),
165 Switch(
166 value: enableAlternativeRoutes,
167 onChanged: (value) {
168 setState(() {
169 enableAlternativeRoutes = value;
170 });
171 navNextBillionMap.toggleAlternativeVisibilityWith(value);
172 })
173 ],
174 ),
175 Row(
176 children: [
177 Text("Display Route Duration Symbol"),
178 Switch(
179 value: enableRouteDurationSymbol,
180 onChanged: (value) {
181 setState(() {
182 enableRouteDurationSymbol = value;
183 });
184 navNextBillionMap.toggleDurationSymbolVisibilityWith(value);
185 })
186 ],
187 )
188 ],
189 ),
190 );
191 }
192}
Code summary
The above code snippet demonstrates how to draw a route line on a map, toggle the visibility of alternative routes, and toggle the visibility of route duration symbols. The app uses the nb_maps_flutter and nb_navigation_flutter packages for map rendering and navigation-related functionality.
Draw Route Line:
- The NBMap widget from the nb_maps_flutter package is used to display the map.
- When the "Fetch Route" button is pressed, the _fetchRoute function is called. It sends a route request to the navigation service (NBNavigation.fetchRoute) with the specified origin and destination coordinates. The response contains a list of DirectionsRoute objects representing different possible routes from the origin to the destination.
- The drawRoutes function is used to draw the fetched routes on the map using the NavNextBillionMap controller.
Toggle Alternative Routes Visibility:
- The "Display Alternative Route" switch allows the user to toggle the visibility of alternative routes on the map.
- The enableAlternativeRoutes variable keeps track of the switch state.
- When the switch is toggled, the _switchButton function calls the toggleAlternativeVisibilityWith method of NavNextBillionMap to change the visibility of alternative routes accordingly.
Toggle Route Duration Symbol Visibility:
-
The "Display Route Duration Symbol" switch allows the user to toggle the visibility of route duration symbols on the map.
-
The enableRouteDurationSymbol variable keeps track of the switch state.
-
When the switch is toggled, the _switchButton function calls the toggleDurationSymbolVisibilityWith method of NavNextBillionMap to change the visibility of route duration symbols accordingly.
Start Navigation:
-
The "Start Navigation" button is used to initiate turn-by-turn navigation using the selected route.
-
When the button is pressed, the _startNavigation function is called. It launches the navigation using NBNavigation.startNavigation with the first route from the list.
Map Interaction:
-
The _onMapCreated callback function is used to get the map controller when the map is created.
-
The _onMapClick function is used to handle map click events. When a route is selected on the map, it is moved to the top of the routes list and redrawn.
-
Overall, the app provides an interface for fetching routes between two specified coordinates, drawing those routes on the map, and toggling the visibility of alternative routes and route duration symbols.