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)
docs-imagedocs-image
Android snapshotiOS snapshot

For all code examples, refer to Flutter Navigation Code Example

DrawRouteLine view source

1import 'dart:math';
2
3import 'package:flutter/foundation.dart';
4import 'package:flutter/material.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 const DrawRouteLine({super.key});
11
12
13 DrawRouteLineState createState() => DrawRouteLineState();
14}
15
16class DrawRouteLineState extends State<DrawRouteLine> {
17 NextbillionMapController? controller;
18 List<DirectionsRoute> routes = [];
19 late NavNextBillionMap navNextBillionMap;
20
21 LatLng origin = const LatLng(
22 17.457302037173775,
23 78.37463792413473,
24 );
25 LatLng dest = const LatLng(
26 17.466320809357967,
27 78.3726774987914,
28 );
29
30 bool enableAlternativeRoutes = true;
31 bool enableRouteDurationSymbol = true;
32
33 void _onMapCreated(NextbillionMapController controller) {
34 this.controller = controller;
35 }
36
37 void _onStyleLoaded() async {
38 if (controller != null) {
39 navNextBillionMap = await NavNextBillionMap.create(controller!);
40 }
41 }
42
43 _onMapClick(Point<double> point, LatLng coordinates) {
44 navNextBillionMap.addRouteSelectedListener(coordinates,
45 (selectedRouteIndex) {
46 if (routes.isNotEmpty && selectedRouteIndex != 0) {
47 var selectedRoute = routes[selectedRouteIndex];
48 routes.removeAt(selectedRouteIndex);
49 routes.insert(0, selectedRoute);
50 setState(() {
51 routes = routes;
52 });
53 navNextBillionMap.drawRoute(routes);
54 }
55 });
56 }
57
58
59 void initState() {
60 super.initState();
61 }
62
63
64 Widget build(BuildContext context) {
65 var screenHeight = MediaQuery.of(context).size.height;
66
67 return Scaffold(
68 appBar: AppBar(
69 title: const Text(DrawRouteLine.title),
70 ),
71 body: SingleChildScrollView(
72 child: Column(
73 children: [
74 Container(
75 constraints: BoxConstraints(maxHeight: screenHeight * 0.6),
76 child: NBMap(
77 onMapCreated: _onMapCreated,
78 initialCameraPosition: CameraPosition(
79 target: LatLng(origin.latitude, origin.longitude),
80 zoom: 13.0,
81 ),
82 onStyleLoadedCallback: _onStyleLoaded,
83 onMapClick: _onMapClick,
84 ),
85 ),
86 _buttonWidget(),
87 _switchButton(),
88 ],
89 ),
90 ),
91 );
92 }
93
94 void _fetchRoute() async {
95 RouteRequestParams requestParams = RouteRequestParams(
96 origin: origin,
97 destination: dest,
98 // waypoints: [Coordinate(latitude: wayP2.latitude, longitude: wayP2.longitude)],
99 // overview: ValidOverview.simplified,
100 // avoid: [SupportedAvoid.toll, SupportedAvoid.ferry],
101 // option: SupportedOption.flexible,
102 // truckSize: [200, 200, 600],
103 // truckWeight: 100,
104 // unit: SupportedUnits.imperial,
105 alternatives: true,
106 mode: ValidModes.car,
107 );
108
109 DirectionsRouteResponse routeResponse =
110 await NBNavigation.fetchRoute(requestParams);
111 if (routeResponse.directionsRoutes.isNotEmpty) {
112 setState(() {
113 routes = routeResponse.directionsRoutes;
114 });
115 drawRoutes(routes);
116 } else if (routeResponse.message != null) {
117 if (kDebugMode) {
118 print(
119 "====error====${routeResponse.message}===${routeResponse.errorCode}");
120 }
121 }
122 }
123
124 void _startNavigation() {
125 if (routes.isEmpty) return;
126 NavigationLauncherConfig config =
127 NavigationLauncherConfig(route: routes.first, routes: routes);
128 config.locationLayerRenderMode = LocationLayerRenderMode.gps;
129 config.themeMode = NavigationThemeMode.system;
130 config.useCustomNavigationStyle = false;
131 NBNavigation.startNavigation(config);
132 }
133
134 Future<void> drawRoutes(List<DirectionsRoute> routes) async {
135 navNextBillionMap.clearRoute();
136 navNextBillionMap.drawRoute(routes);
137 }
138
139
140 void dispose() {
141 super.dispose();
142 }
143
144 _buttonWidget() {
145 return Padding(
146 padding: const EdgeInsets.only(left: 8, top: 18.0),
147 child: Row(
148 children: [
149 ElevatedButton(
150 style: ButtonStyle(
151 backgroundColor: WidgetStateProperty.all(Colors.blueAccent),
152 ),
153 onPressed: () {
154 _fetchRoute();
155 },
156 child: const Text("Fetch Route"),
157 ),
158 const Padding(padding: EdgeInsets.only(left: 8)),
159 ElevatedButton(
160 style: ButtonStyle(
161 backgroundColor: WidgetStateProperty.all(
162 routes.isEmpty ? Colors.grey : Colors.blueAccent),
163 enableFeedback: routes.isNotEmpty),
164 onPressed: () {
165 _startNavigation();
166 },
167 child: const Text("Start Navigation"),
168 ),
169 ],
170 ),
171 );
172 }
173
174 _switchButton() {
175 return Padding(
176 padding: const EdgeInsets.all(8.0),
177 child: Column(
178 mainAxisAlignment: MainAxisAlignment.end,
179 crossAxisAlignment: CrossAxisAlignment.start,
180 children: [
181 Row(
182 children: [
183 const Text("Display Alternative Route"),
184 Switch(
185 value: enableAlternativeRoutes,
186 onChanged: (value) {
187 setState(() {
188 enableAlternativeRoutes = value;
189 });
190 navNextBillionMap.toggleAlternativeVisibilityWith(value);
191 })
192 ],
193 ),
194 Row(
195 children: [
196 const Text("Display Route Duration Symbol"),
197 Switch(
198 value: enableRouteDurationSymbol,
199 onChanged: (value) async {
200 setState(() {
201 enableRouteDurationSymbol = value;
202 });
203 navNextBillionMap.toggleDurationSymbolVisibilityWith(value);
204 })
205 ],
206 )
207 ],
208 ),
209 );
210 }
211}

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.