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_getWeight]
146 // Get total route weight
147 val weight = routePath.weight
148 println("Route weight: $weight")
149 // [kotlin_RoutePath_getWeight]
150
151 // [kotlin_RoutePath_getNodes]
152 // Get route nodes
153 val nodes = routePath.nodes
154 println("Number of route nodes: ${nodes.size}")
155 nodes.take(3).forEach { node ->
156 demonstrateRouteNodeUsage(node)
157 }
158 // [kotlin_RoutePath_getNodes]
159
160 // [kotlin_RoutePath_head]
161 // Get route head (first 10 meters)
162 val head = routePath.head(10.0)
163 head?.let {
164 println("Route head length: ${it.length} meters")
165 }
166 // [kotlin_RoutePath_head]
167
168 // [kotlin_RoutePath_tail]
169 // Get route tail (remaining after 10 meters)
170 val tail = routePath.tail(10.0)
171 tail?.let {
172 println("Route tail length: ${it.length} meters")
173 }
174 // [kotlin_RoutePath_tail]
175 }
176
177 fun demonstrateRouteNodeUsage(node: RouteNode) {
178 // [kotlin_RouteNode_getPoint]
179 val point = node.point
180 demonstrateLocationPointUsage(point)
181 // [kotlin_RouteNode_getPoint]
182
183 // [kotlin_RouteNode_getWeight]
184 val weight = node.weight
185 println("Node weight: $weight")
186 // [kotlin_RouteNode_getWeight]
187
188 // [kotlin_RouteNode_getDistance]
189 val distance = node.distance
190 println("Node distance: $distance meters")
191 // [kotlin_RouteNode_getDistance]
192
193 // [kotlin_RouteNode_getEvents]
194 val events = node.events
195 events.forEach { demonstrateRouteEventUsage(it) }
196 // [kotlin_RouteNode_getEvents]
197 }
198
199 /**
200 * Demonstrate RouteEvent usage
201 */
202 fun demonstrateRouteEventUsage(event: RouteEvent) {
203 if (event == null) {
204 System.err.println("RouteEvent is null")
205 return
206 }
207
208 // [kotlin_RouteEvent_getType]
209 // Get event type
210 val type = event.type
211 println("Event type: $type")
212 // [kotlin_RouteEvent_getType]
213
214 // [kotlin_RouteEvent_getTurnEvent]
215 val turnEvent = event.turnEvent
216 turnEvent?.let { demonstrateTurnEventUsage(it) }
217 // [kotlin_RouteEvent_getTurnEvent]
218
219 // [kotlin_RouteEvent_getTransitionEntryEvent]
220 val entryEvent = event.transitionEntryEvent
221 entryEvent?.let { demonstrateTransitionEntryEventUsage(it) }
222 // [kotlin_RouteEvent_getTransitionEntryEvent]
223
224 // [kotlin_RouteEvent_getTransitionExitEvent]
225 val exitEvent = event.transitionExitEvent
226 exitEvent?.let { demonstrateTransitionExitEventUsage(it) }
227 // [kotlin_RouteEvent_getTransitionExitEvent]
228
229 // [kotlin_RouteEvent_getTargetReachedEvent]
230 val reachedEvent = event.targetReachedEvent
231 reachedEvent?.let { demonstrateTargetReachedEventUsage(it) }
232 // [kotlin_RouteEvent_getTargetReachedEvent]
233 }
234
235 /**
236 * Demonstrate RouteEventType enum values
237 */
238 fun demonstrateRouteEventTypes() {
239 // [kotlin_RouteEventType_values]
240 // Get all route event type values
241 val types = RouteEventType.values()
242 println("Available route event types:")
243 types.forEach { type ->
244 println(" - $type")
245 }
246 // [kotlin_RouteEventType_values]
247 }
248
249 fun demonstrateTurnTypes() {
250 // [kotlin_TurnType_values]
251 val types = TurnType.values()
252 types.forEach { println(" - $it") }
253 // [kotlin_TurnType_values]
254 }
255
256 fun demonstrateTurnEventUsage(event: TurnEvent) {
257 // [kotlin_TurnEvent_getType]
258 val type = event.type
259 println("Turn type: $type")
260 // [kotlin_TurnEvent_getType]
261
262 // [kotlin_TurnEvent_getAngle]
263 val angle = event.angle
264 println("Turn angle: $angle")
265 // [kotlin_TurnEvent_getAngle]
266 }
267
268 fun demonstrateTransitionEntryEventUsage(event: TransitionEntryEvent) {
269 // [kotlin_TransitionEntryEvent_getFrom]
270 val from = event.from
271 println("Transition entry from: $from")
272 // [kotlin_TransitionEntryEvent_getFrom]
273
274 // [kotlin_TransitionEntryEvent_getTo]
275 val to = event.to
276 println("Transition entry to: $to")
277 // [kotlin_TransitionEntryEvent_getTo]
278 }
279
280 fun demonstrateTransitionExitEventUsage(event: TransitionExitEvent) {
281 // [kotlin_TransitionExitEvent_getFrom]
282 val from = event.from
283 println("Transition exit from: $from")
284 // [kotlin_TransitionExitEvent_getFrom]
285
286 // [kotlin_TransitionExitEvent_getTo]
287 val to = event.to
288 println("Transition exit to: $to")
289 // [kotlin_TransitionExitEvent_getTo]
290 }
291
292 fun demonstrateTargetReachedEventUsage(event: TargetReachedEvent) {
293 // [kotlin_TargetReachedEvent_getIndex]
294 val index = event.index
295 println("Reached target index: $index")
296 // [kotlin_TargetReachedEvent_getIndex]
297
298 // [kotlin_TargetReachedEvent_getPoint]
299 val point = event.point
300 demonstrateLocationPointUsage(point)
301 // [kotlin_TargetReachedEvent_getPoint]
302 }
303
304 /**
305 * Demonstrate LocationPoint usage
306 */
307 fun demonstrateLocationPointUsage(locationPoint: LocationPoint) {
308 if (locationPoint == null) {
309 System.err.println("LocationPoint is null")
310 return
311 }
312
313 // [kotlin_LocationPoint_getPoint]
314 // Get point coordinates
315 val point = locationPoint.point
316 println("Location point: (${point.x}, ${point.y})")
317 // [kotlin_LocationPoint_getPoint]
318
319 // [kotlin_LocationPoint_getLocationId]
320 // Get location ID
321 val locationId = locationPoint.locationId
322 println("Location ID: $locationId")
323 // [kotlin_LocationPoint_getLocationId]
324
325 // [kotlin_LocationPoint_getSublocationId]
326 // Get sublocation ID
327 val sublocationId = locationPoint.sublocationId
328 println("Sublocation ID: $sublocationId")
329 // [kotlin_LocationPoint_getSublocationId]
330
331 // [kotlin_LocationPoint_constructor]
332 // Create new location point
333 val newPoint = Point(25.0, 35.0)
334 val newLocationPoint = LocationPoint(newPoint, 12345, 2)
335 println("Created new location point: ${newLocationPoint.point.x}, ${newLocationPoint.point.y}")
336 // [kotlin_LocationPoint_constructor]
337 }
338
339 /**
340 * Demonstrate Point usage
341 */
342 fun demonstratePointUsage(point: Point) {
343 if (point == null) {
344 System.err.println("Point is null")
345 return
346 }
347
348 // [kotlin_Point_getX]
349 // Get X coordinate
350 val x = point.x
351 println("Point X: $x")
352 // [kotlin_Point_getX]
353
354 // [kotlin_Point_getY]
355 // Get Y coordinate
356 val y = point.y
357 println("Point Y: $y")
358 // [kotlin_Point_getY]
359
360 // [kotlin_Point_constructor]
361 // Create new point
362 val newPoint = Point(15.0, 25.0)
363 println("Created new point: (${newPoint.x}, ${newPoint.y})")
364 // [kotlin_Point_constructor]
365 }
366
367 /**
368 * Demonstrate RouteOptions usage
369 */
370 fun demonstrateRouteOptions() {
371 println("=== Route Options ===")
372
373 // [kotlin_RouteOptions_constructor]
374 // Create route options with custom parameters
375 val routeOptions = RouteOptions(3.0, 7.0, 2.5)
376 println("Created route options with smoothRadius: ${routeOptions.smoothRadius}, maxProjectionDistance: ${routeOptions.maxProjectionDistance}, maxAdvance: ${routeOptions.maxAdvance}")
377 // [kotlin_RouteOptions_constructor]
378
379 // Demonstrate different route options configurations
380 val optionsList = listOf(
381 RouteOptions(0.0, 5.0, 2.0), // No smoothing
382 RouteOptions(2.0, 10.0, 1.0), // High smoothing, high projection distance
383 RouteOptions(1.0, 3.0, 3.0), // Low smoothing, low projection distance
384 )
385
386 optionsList.forEachIndexed { index, options ->
387 println("Options ${index + 1}: smoothRadius=${options.smoothRadius}, maxProjectionDistance=${options.maxProjectionDistance}, maxAdvance=${options.maxAdvance}")
388 }
389 }
390
391 /**
392 * Demonstrate advanced async routing features
393 */
394 suspend fun demonstrateAdvancedAsyncRoutingFeatures() {
395 println("=== Advanced Async Routing Features ===")
396
397 val manager = asyncRouteManager ?: return
398
399 // Create multiple destination points
400 val destinations = listOf(
401 LocationPoint(Point(50.0, 50.0), 12345, 1),
402 LocationPoint(Point(100.0, 100.0), 12345, 1),
403 LocationPoint(Point(150.0, 150.0), 12345, 1)
404 )
405
406 // Create different route options for each destination
407 val optionsList = listOf(
408 RouteOptions(2.0, 5.0, 2.0),
409 RouteOptions(3.0, 7.0, 1.5),
410 RouteOptions(1.0, 3.0, 2.5),
411 )
412
413 // Create sessions for each destination
414 val sessions = mutableListOf<RouteSession>()
415 destinations.forEachIndexed { index, destination ->
416 val session = manager.createRouteSession(destination, optionsList[index])
417 sessions.add(session)
418 println("Created session ${index + 1} for destination: ${destination.point.x}, ${destination.point.y}")
419
420 asyncRouteListener?.let { listener ->
421 session.addRouteListener(listener)
422 }
423
424 delay(1000)
425 }
426
427 // Wait for route updates
428 delay(3000)
429
430 // Cancel all sessions
431 sessions.forEachIndexed { index, session ->
432 // [kotlin_AsyncRouteManager_cancelRouteSession]
433 // Cancel route session
434 manager.cancelRouteSession(session)
435 println("Cancelled session ${index + 1}")
436 // [kotlin_AsyncRouteManager_cancelRouteSession]
437
438 delay(1000)
439 }
440 }
441
442 /**
443 * Demonstrate RouteStatus enum usage
444 */
445 fun demonstrateRouteStatusUsage() {
446 println("=== RouteStatus Enum Usage ===")
447
448 // [kotlin_RouteStatus_values]
449 // Demonstrate all RouteStatus values
450 println("Available RouteStatus values:")
451 RouteStatus.values().forEach { status ->
452 println(" - ${status.name}: $status")
453 }
454
455 // Demonstrate status checking
456 val testStatus = RouteStatus.NEW_ROUTE
457 when (testStatus) {
458 RouteStatus.NEW_ROUTE -> println("Router is ready for navigation")
459 RouteStatus.MISSING_GRAPH -> println("Router is missing the route graph")
460 RouteStatus.MISSING_POSITION -> println("Router is missing the current position")
461 RouteStatus.MISSING_PROJECTION -> println("Current position is off the route graph")
462 RouteStatus.MISSING_ROUTE -> println("Router unable to find the route to the destination point")
463 }
464 // [kotlin_RouteStatus_values]
465 }
466
467 /**
468 * Demonstrate route session management
469 */
470 fun demonstrateRouteSessionManagement() {
471 println("=== Route Session Management ===")
472
473 val manager = asyncRouteManager
474 val listener = asyncRouteListener
475 if (manager == null || listener == null) {
476 return
477 }
478
479 // Create test destination
480 val destinationPoint = Point(75.0, 75.0)
481 val destinationLocationPoint = LocationPoint(destinationPoint, 12345, 1)
482 val routeOptions = RouteOptions(2.0, 5.0, 2.0)
483
484 // Create session with default tag
485 val defaultSession = manager.createRouteSession(destinationLocationPoint, routeOptions)
486 println("Created session with default tag")
487
488 // Create session with specific tag
489 val taggedSession = manager.createRouteSessionWithTag(destinationLocationPoint, routeOptions, "elevator")
490 println("Created session with 'elevator' tag")
491
492 // Add listeners to both sessions
493 defaultSession.addRouteListener(listener)
494 taggedSession.addRouteListener(listener)
495
496 // Simulate some time passing
497 GlobalScope.launch {
498 delay(2000)
499
500 // Remove listeners
501 // [kotlin_RouteSession_removeRouteListener1]
502 // Remove route listener from session
503 defaultSession.removeRouteListener(listener)
504 taggedSession.removeRouteListener(listener)
505 println("Removed listeners from sessions")
506 // [kotlin_RouteSession_removeRouteListener1]
507
508 // Cancel sessions
509 manager.cancelRouteSession(defaultSession)
510 manager.cancelRouteSession(taggedSession)
511 println("Cancelled both sessions")
512 }
513 }
514
515 /**
516 * Clean up resources
517 */
518 fun cleanup() {
519 val session = currentSession
520 val listener = asyncRouteListener
521 if (session != null && listener != null) {
522 // [kotlin_RouteSession_removeRouteListener]
523 // Remove route listener
524 session.removeRouteListener(listener)
525 // [kotlin_RouteSession_removeRouteListener]
526 }
527
528 val manager = asyncRouteManager
529 if (manager != null && session != null) {
530 // [kotlin_AsyncRouteManager_cancelRouteSession_1]
531 // Cancel route session
532 manager.cancelRouteSession(session)
533 // [kotlin_AsyncRouteManager_cancelRouteSession_1]
534 }
535 }
536
537 /**
538 * Main demonstration method
539 */
540 suspend fun runExample() {
541 println("=== AsyncRouteManager Example ===")
542
543 demonstrateAsyncRouteManagerMethods()
544 demonstrateRouteEventTypes()
545 demonstrateTurnTypes()
546 demonstrateRouteOptions()
547 demonstrateRouteStatusUsage()
548 demonstrateRouteSessionManagement()
549 demonstrateAdvancedAsyncRoutingFeatures()
550
551 // Wait a bit for route updates
552 delay(3000)
553
554 cleanup()
555 println("=== Example completed ===")
556 }
557}
558
559/**
560 * Function to run the example
561 */
562fun main() = runBlocking {
563 val example = AsyncRouteManagerExample()
564 example.runExample()
565}