Routing | Mobile SDK | 2GIS Documentation


In order to create a route on the map, you need to create two objects: TrafficRouter to find an optimal route and RouteMapObjectSource to display it on the map.

To find a route between two points, call the findRoute() method and specify the coordinates of the start and end points as RouteSearchPoint objects. You can additionally specify a list of intermediate points of the route and RouteSearchOptions.

val startSearchPoint = RouteSearchPoint(
    coordinates = GeoPoint(latitude = 55.759909, longitude = 37.618806)
val finishSearchPoint = RouteSearchPoint(
    coordinates = GeoPoint(latitude = 55.752425, longitude = 37.613983)

val trafficRouter = TrafficRouter(sdkContext)
val routesFuture = trafficRouter.findRoute(startSearchPoint, finishSearchPoint)

The findRoute() call will return a deferred result with a list of TrafficRoute objects. To display the found route on the map, you need to use these objects to create RouteMapObject objects and add them to a RouteMapObjectSource data source.

// Create a data source
let routeMapObjectSource = RouteMapObjectSource(context: sdk.context, routeVisualizationType: .normal)
map.addSource(source: routeMapObjectSource)

// Find a route
self.routeSearchCancellable = routesFuture.sink { routes in
	// After receiving the route, add it to the map
	for (index, route) in routes.enumerated() {
		let routeMapObject = RouteMapObject(
			route: route,
			isActive: index == 0,
			index: RouteIndex(value: UInt64(index)),
			displayFlags: nil
		routeMapObjectSource.addObject(item: routeMapObject)
} failure: { error in
	print("Can't find route: \(error)")