Loading...
Searching...
No Matches
AsyncRouteManagerExample.kt
Go to the documentation of this file.
1import kotlinx.coroutines.delay
2import kotlinx.coroutines.runBlocking
3import kotlinx.coroutines.GlobalScope
4import kotlinx.coroutines.launch
5
6/**
7 * AsyncRouteManager usage example for Kotlin
8 * Demonstrates working with async route planning, session management, and navigation
9 */
10class AsyncRouteManagerExample {
11 private var sdk: NavigineSdk? = null
12 private var locationManager: LocationManager? = null
13 private var navigationManager: NavigationManager? = null
14 private var asyncRouteManager: AsyncRouteManager? = null
15 private var asyncRouteListener: AsyncRouteListener? = null
16 private var currentSession: RouteSession? = null
17
18 init {
19 initializeSdk()
20 setupAsyncRouteListener()
21 }
22
23 /**
24 * Initialize SDK and get managers
25 */
26 private fun initializeSdk() {
27 try {
28 // [kotlin_NavigineSdk_getInstance]
29 // Get SDK instance
30 sdk = NavigineSdk.getInstance()
31 // [kotlin_NavigineSdk_getInstance]
32
33 // [kotlin_NavigineSdk_setUserHash]
34 // Set user hash
35 sdk?.setUserHash("USER-HASH-HERE")
36 // [kotlin_NavigineSdk_setUserHash]
37
38 // [kotlin_NavigineSdk_setServer]
39 // Set server URL (optional)
40 sdk?.setServer("https://custom.navigine.com")
41 // [kotlin_NavigineSdk_setServer]
42
43 // [kotlin_NavigineSdk_getLocationManager]
44 // Get LocationManager for working with locations
45 locationManager = sdk?.getLocationManager()
46 // [kotlin_NavigineSdk_getLocationManager]
47
48 // [kotlin_NavigineSdk_getNavigationManager]
49 // Get NavigationManager for working with navigation
50 navigationManager = sdk?.getNavigationManager(locationManager)
51 // [kotlin_NavigineSdk_getNavigationManager]
52
53 // [kotlin_NavigineSdk_getAsyncRouteManager]
54 // Get AsyncRouteManager for working with async routes
55 asyncRouteManager = sdk?.getAsyncRouteManager(locationManager, navigationManager)
56 // [kotlin_NavigineSdk_getAsyncRouteManager]
57
58 if (locationManager != null && navigationManager != null && asyncRouteManager != null) {
59 println("LocationManager, NavigationManager and AsyncRouteManager successfully initialized")
60 }
61 } catch (e: Exception) {
62 System.err.println("Error initializing SDK: ${e.message}")
63 }
64 }
65
66 /**
67 * Setup async route listener
68 */
69 private fun setupAsyncRouteListener() {
70 asyncRouteListener = object : AsyncRouteListener() {
71 // [kotlin_AsyncRouteListener_onRouteChanged]
72 override fun onRouteChanged(status: RouteStatus, currentPath: RoutePath) {
73 println("Route changed with status: $status")
74 if (status == RouteStatus.NEW_ROUTE && currentPath != null) {
75 demonstrateRoutePathUsage(currentPath)
76 } else {
77 println("Route not ready, status: $status")
78 }
79 }
80 // [kotlin_AsyncRouteListener_onRouteChanged]
81
82 // [kotlin_AsyncRouteListener_onRouteAdvanced]
83 override fun onRouteAdvanced(distance: Float, point: LocationPoint) {
84 println("Route advanced: $distance meters")
85 demonstrateLocationPointUsage(point)
86 }
87 // [kotlin_AsyncRouteListener_onRouteAdvanced]
88 }
89 }
90
91 /**
92 * Demonstrate AsyncRouteManager methods
93 */
94 fun demonstrateAsyncRouteManagerMethods() {
95 val manager = asyncRouteManager ?: run {
96 System.err.println("AsyncRouteManager not initialized")
97 return
98 }
99
100 // Create test destination point
101 val destinationPoint = Point(100.0, 100.0)
102 val destinationLocationPoint = LocationPoint(destinationPoint, 12345, 1)
103
104 // Create route options
105 val routeOptions = RouteOptions(2.0, 5.0, 2.0)
106
107 // [kotlin_AsyncRouteManager_createRouteSession]
108 // Create route session with default graph tag
109 val session = manager.createRouteSession(destinationLocationPoint, routeOptions)
110 println("Created route session with default graph tag")
111 // [kotlin_AsyncRouteManager_createRouteSession]
112
113 // [kotlin_AsyncRouteManager_createRouteSessionWithTag]
114 // Create route session with specific graph tag
115 val sessionWithTag = manager.createRouteSessionWithTag(destinationLocationPoint, routeOptions, "main")
116 println("Created route session with 'main' graph tag")
117 // [kotlin_AsyncRouteManager_createRouteSessionWithTag]
118
119 // Store session for later use
120 currentSession = session
121
122 // Add listener to session
123 val listener = asyncRouteListener ?: return
124 // [kotlin_RouteSession_addRouteListener]
125 // Add route listener to session
126 session.addRouteListener(listener)
127 // [kotlin_RouteSession_addRouteListener]
128 }
129
130 /**
131 * Demonstrate RoutePath usage
132 */
133 fun demonstrateRoutePathUsage(routePath: RoutePath) {
134 if (routePath == null) {
135 System.err.println("RoutePath is null")
136 return
137 }
138
139 // [kotlin_RoutePath_getLength]
140 // Get route length
141 val length = routePath.length
142 println("Route length: $length meters")
143 // [kotlin_RoutePath_getLength]
144
145 // [kotlin_RoutePath_getPoints]
146 // Get route points
147 val points = routePath.points
148 println("Number of route points: ${points.size}")
149 points.take(3).forEachIndexed { index, point ->
150 println("Point ${index + 1}: $point")
151 }
152 // [kotlin_RoutePath_getPoints]
153
154 // [kotlin_RoutePath_getEvents]
155 // Get route events
156 val events = routePath.events
157 println("Number of route events: ${events.size}")
158 events.take(3).forEach { event ->
159 demonstrateRouteEventUsage(event)
160 }
161 // [kotlin_RoutePath_getEvents]
162
163 // [kotlin_RoutePath_head]
164 // Get route head (first 10 meters)
165 val head = routePath.head(10.0)
166 head?.let {
167 println("Route head length: ${it.length} meters")
168 }
169 // [kotlin_RoutePath_head]
170
171 // [kotlin_RoutePath_tail]
172 // Get route tail (remaining after 10 meters)
173 val tail = routePath.tail(10.0)
174 tail?.let {
175 println("Route tail length: ${it.length} meters")
176 }
177 // [kotlin_RoutePath_tail]
178 }
179
180 /**
181 * Demonstrate RouteEvent usage
182 */
183 fun demonstrateRouteEventUsage(event: RouteEvent) {
184 if (event == null) {
185 System.err.println("RouteEvent is null")
186 return
187 }
188
189 // [kotlin_RouteEvent_getType]
190 // Get event type
191 val type = event.type
192 println("Event type: $type")
193 // [kotlin_RouteEvent_getType]
194
195 // [kotlin_RouteEvent_getValue]
196 // Get event value
197 val value = event.value
198 println("Event value: $value")
199 // [kotlin_RouteEvent_getValue]
200
201 // [kotlin_RouteEvent_getDistance]
202 // Get event distance
203 val distance = event.distance
204 println("Event distance: $distance meters")
205 // [kotlin_RouteEvent_getDistance]
206
207 // [kotlin_RouteEvent_constructor]
208 // Create new route event
209 val newEvent = RouteEvent(RouteEventType.TURN_LEFT, 90, 50.0)
210 println("Created new route event: ${newEvent.type} at ${newEvent.distance} meters")
211 // [kotlin_RouteEvent_constructor]
212 }
213
214 /**
215 * Demonstrate RouteEventType enum values
216 */
217 fun demonstrateRouteEventTypes() {
218 // [kotlin_RouteEventType_values]
219 // Get all route event type values
220 val types = RouteEventType.values()
221 println("Available route event types:")
222 types.forEach { type ->
223 println(" - $type")
224 }
225 // [kotlin_RouteEventType_values]
226 }
227
228 /**
229 * Demonstrate LocationPoint usage
230 */
231 fun demonstrateLocationPointUsage(locationPoint: LocationPoint) {
232 if (locationPoint == null) {
233 System.err.println("LocationPoint is null")
234 return
235 }
236
237 // [kotlin_LocationPoint_getPoint]
238 // Get point coordinates
239 val point = locationPoint.point
240 println("Location point: (${point.x}, ${point.y})")
241 // [kotlin_LocationPoint_getPoint]
242
243 // [kotlin_LocationPoint_getLocationId]
244 // Get location ID
245 val locationId = locationPoint.locationId
246 println("Location ID: $locationId")
247 // [kotlin_LocationPoint_getLocationId]
248
249 // [kotlin_LocationPoint_getSublocationId]
250 // Get sublocation ID
251 val sublocationId = locationPoint.sublocationId
252 println("Sublocation ID: $sublocationId")
253 // [kotlin_LocationPoint_getSublocationId]
254
255 // [kotlin_LocationPoint_constructor]
256 // Create new location point
257 val newPoint = Point(25.0, 35.0)
258 val newLocationPoint = LocationPoint(newPoint, 12345, 2)
259 println("Created new location point: ${newLocationPoint.point.x}, ${newLocationPoint.point.y}")
260 // [kotlin_LocationPoint_constructor]
261 }
262
263 /**
264 * Demonstrate Point usage
265 */
266 fun demonstratePointUsage(point: Point) {
267 if (point == null) {
268 System.err.println("Point is null")
269 return
270 }
271
272 // [kotlin_Point_getX]
273 // Get X coordinate
274 val x = point.x
275 println("Point X: $x")
276 // [kotlin_Point_getX]
277
278 // [kotlin_Point_getY]
279 // Get Y coordinate
280 val y = point.y
281 println("Point Y: $y")
282 // [kotlin_Point_getY]
283
284 // [kotlin_Point_constructor]
285 // Create new point
286 val newPoint = Point(15.0, 25.0)
287 println("Created new point: (${newPoint.x}, ${newPoint.y})")
288 // [kotlin_Point_constructor]
289 }
290
291 /**
292 * Demonstrate RouteOptions usage
293 */
294 fun demonstrateRouteOptions() {
295 println("=== Route Options ===")
296
297 // [kotlin_RouteOptions_constructor]
298 // Create route options with custom parameters
299 val routeOptions = RouteOptions(3.0, 7.0, 2.5)
300 println("Created route options with smoothRadius: ${routeOptions.smoothRadius}, maxProjectionDistance: ${routeOptions.maxProjectionDistance}, maxAdvance: ${routeOptions.maxAdvance}")
301 // [kotlin_RouteOptions_constructor]
302
303 // Demonstrate different route options configurations
304 val optionsList = listOf(
305 RouteOptions(0.0, 5.0, 2.0), // No smoothing
306 RouteOptions(2.0, 10.0, 1.0), // High smoothing, high projection distance
307 RouteOptions(1.0, 3.0, 3.0), // Low smoothing, low projection distance
308 )
309
310 optionsList.forEachIndexed { index, options ->
311 println("Options ${index + 1}: smoothRadius=${options.smoothRadius}, maxProjectionDistance=${options.maxProjectionDistance}, maxAdvance=${options.maxAdvance}")
312 }
313 }
314
315 /**
316 * Demonstrate advanced async routing features
317 */
318 suspend fun demonstrateAdvancedAsyncRoutingFeatures() {
319 println("=== Advanced Async Routing Features ===")
320
321 val manager = asyncRouteManager ?: return
322
323 // Create multiple destination points
324 val destinations = listOf(
325 LocationPoint(Point(50.0, 50.0), 12345, 1),
326 LocationPoint(Point(100.0, 100.0), 12345, 1),
327 LocationPoint(Point(150.0, 150.0), 12345, 1)
328 )
329
330 // Create different route options for each destination
331 val optionsList = listOf(
332 RouteOptions(2.0, 5.0, 2.0),
333 RouteOptions(3.0, 7.0, 1.5),
334 RouteOptions(1.0, 3.0, 2.5),
335 )
336
337 // Create sessions for each destination
338 val sessions = mutableListOf<RouteSession>()
339 destinations.forEachIndexed { index, destination ->
340 val session = manager.createRouteSession(destination, optionsList[index])
341 sessions.add(session)
342 println("Created session ${index + 1} for destination: ${destination.point.x}, ${destination.point.y}")
343
344 asyncRouteListener?.let { listener ->
345 session.addRouteListener(listener)
346 }
347
348 delay(1000)
349 }
350
351 // Wait for route updates
352 delay(3000)
353
354 // Cancel all sessions
355 sessions.forEachIndexed { index, session ->
356 // [kotlin_AsyncRouteManager_cancelRouteSession]
357 // Cancel route session
358 manager.cancelRouteSession(session)
359 println("Cancelled session ${index + 1}")
360 // [kotlin_AsyncRouteManager_cancelRouteSession]
361
362 delay(1000)
363 }
364 }
365
366 /**
367 * Demonstrate RouteStatus enum usage
368 */
369 fun demonstrateRouteStatusUsage() {
370 println("=== RouteStatus Enum Usage ===")
371
372 // [kotlin_RouteStatus_values]
373 // Demonstrate all RouteStatus values
374 println("Available RouteStatus values:")
375 RouteStatus.values().forEach { status ->
376 println(" - ${status.name}: $status")
377 }
378
379 // Demonstrate status checking
380 val testStatus = RouteStatus.NEW_ROUTE
381 when (testStatus) {
382 RouteStatus.NEW_ROUTE -> println("Router is ready for navigation")
383 RouteStatus.MISSING_GRAPH -> println("Router is missing the route graph")
384 RouteStatus.MISSING_POSITION -> println("Router is missing the current position")
385 RouteStatus.MISSING_PROJECTION -> println("Current position is off the route graph")
386 RouteStatus.MISSING_ROUTE -> println("Router unable to find the route to the destination point")
387 }
388 // [kotlin_RouteStatus_values]
389 }
390
391 /**
392 * Demonstrate route session management
393 */
394 fun demonstrateRouteSessionManagement() {
395 println("=== Route Session Management ===")
396
397 val manager = asyncRouteManager
398 val listener = asyncRouteListener
399 if (manager == null || listener == null) {
400 return
401 }
402
403 // Create test destination
404 val destinationPoint = Point(75.0, 75.0)
405 val destinationLocationPoint = LocationPoint(destinationPoint, 12345, 1)
406 val routeOptions = RouteOptions(2.0, 5.0, 2.0)
407
408 // Create session with default tag
409 val defaultSession = manager.createRouteSession(destinationLocationPoint, routeOptions)
410 println("Created session with default tag")
411
412 // Create session with specific tag
413 val taggedSession = manager.createRouteSessionWithTag(destinationLocationPoint, routeOptions, "elevator")
414 println("Created session with 'elevator' tag")
415
416 // Add listeners to both sessions
417 defaultSession.addRouteListener(listener)
418 taggedSession.addRouteListener(listener)
419
420 // Simulate some time passing
421 GlobalScope.launch {
422 delay(2000)
423
424 // Remove listeners
425 // [kotlin_RouteSession_removeRouteListener]
426 // Remove route listener from session
427 defaultSession.removeRouteListener(listener)
428 taggedSession.removeRouteListener(listener)
429 println("Removed listeners from sessions")
430 // [kotlin_RouteSession_removeRouteListener]
431
432 // Cancel sessions
433 manager.cancelRouteSession(defaultSession)
434 manager.cancelRouteSession(taggedSession)
435 println("Cancelled both sessions")
436 }
437 }
438
439 /**
440 * Clean up resources
441 */
442 fun cleanup() {
443 val session = currentSession
444 val listener = asyncRouteListener
445 if (session != null && listener != null) {
446 // [kotlin_RouteSession_removeRouteListener]
447 // Remove route listener
448 session.removeRouteListener(listener)
449 // [kotlin_RouteSession_removeRouteListener]
450 }
451
452 val manager = asyncRouteManager
453 if (manager != null && session != null) {
454 // [kotlin_AsyncRouteManager_cancelRouteSession_1]
455 // Cancel route session
456 manager.cancelRouteSession(session)
457 // [kotlin_AsyncRouteManager_cancelRouteSession_1]
458 }
459 }
460
461 /**
462 * Main demonstration method
463 */
464 suspend fun runExample() {
465 println("=== AsyncRouteManager Example ===")
466
467 demonstrateAsyncRouteManagerMethods()
468 demonstrateRouteEventTypes()
469 demonstrateRouteOptions()
470 demonstrateRouteStatusUsage()
471 demonstrateRouteSessionManagement()
472 demonstrateAdvancedAsyncRoutingFeatures()
473
474 // Wait a bit for route updates
475 delay(3000)
476
477 cleanup()
478 println("=== Example completed ===")
479 }
480}
481
482/**
483 * Function to run the example
484 */
485fun main() = runBlocking {
486 val example = AsyncRouteManagerExample()
487 example.runExample()
488}