# Calculate Route

Last updated:

<!-- -->

October 18, 2026

<!-- -->

\| 4 minutes read

<br />

<br />

* UIKit
* SwiftUI

This example demonstrates how to use **GEMKit** in a UIKit application to calculate a car route between two coordinates and display it on the map with a summary panel.

Check the full implementation on [GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/UIKit/RoutesAndNavigation/CalculateRoute).

![Calculated Route with Insets](/docs/ios/assets/images/example_ios_calculate_route-90cb529a0245c53736ddd852bc4535ab.png)

**Calculated Route with Insets**

### UI and Map Integration[​](#ui-and-map-integration "Direct link to UI and Map Integration")

The following code outlines the main view controller and the embedded map view setup:

ViewController.swift[View on GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/UIKit/RoutesAndNavigation/CalculateRoute/CalculateRoute/ViewController.swift)

```swift
class ViewController: UIViewController, UISearchBarDelegate {

    var mapViewController: MapViewController?

    var navigationContext: NavigationContext?

    var trafficContext: TrafficContext?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "Calculate Route"
        self.navigationItem.largeTitleDisplayMode = .never

        self.createMapView()

        self.mapViewController!.startRender()

        self.addRouteButton()
    }

    // MARK: - Map View

    func createMapView() {

        self.mapViewController = MapViewController.init()
        self.mapViewController!.view.backgroundColor = UIColor.systemBackground

        self.addChild(self.mapViewController!)
        self.view.addSubview(self.mapViewController!.view)
        self.mapViewController!.didMove(toParent: self)

        self.mapViewController?.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.mapViewController!.view.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.mapViewController!.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.mapViewController!.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            self.mapViewController!.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
        ])
    }

```

### Setting Route Preferences and Calculating[​](#setting-route-preferences-and-calculating "Direct link to Setting Route Preferences and Calculating")

Route preferences are configured on a `RoutePreferencesObject`, then passed to a `NavigationContext` which performs the calculation. A `TrafficContext` is used to overlay live traffic data on the result:

ViewController.swift[View on GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/UIKit/RoutesAndNavigation/CalculateRoute/CalculateRoute/ViewController.swift)

```swift
    @objc func routeButtonAction(item: UIBarButtonItem) {

        if self.navigationContext == nil {

            let preferences = RoutePreferencesObject.init()
            preferences.setTransportMode(.car)
            preferences.setRouteType(.fastest)
            preferences.setAvoidMotorways(false)
            preferences.setAvoidTollRoads(false)
            preferences.setAvoidFerries(false)
            preferences.setAvoidUnpavedRoads(true)

            self.navigationContext = NavigationContext.init(preferences: preferences)
        }

        if self.trafficContext == nil {

            self.trafficContext = TrafficContext.init()
            self.trafficContext?.setUseTraffic(.useOnline)
        }

        let waypoints = [

            LandmarkObject.landmark(
                withName: "San Francisco", location: CoordinatesObject.coordinates(withLatitude: 37.77903, longitude: -122.41991)),
            LandmarkObject.landmark(
                withName: "San Jose", location: CoordinatesObject.coordinates(withLatitude: 37.33619, longitude: -121.89058))
        ]

        item.isEnabled = false

        self.navigationContext?
            .calculateRoute(
                withWaypoints: waypoints,
                completionHandler: { [weak self] (results: [RouteObject]) in

                    guard let strongSelf = self else { return }

                    if !results.isEmpty {

                        let insets = strongSelf.areaEdge(margin: 70)

                        strongSelf.mapViewController?.setEdgeAreaInsets(insets)

                        strongSelf.mapViewController?
                            .presentRoutes(results, withTraffic: strongSelf.trafficContext, showSummary: true, animationDuration: 1600)
                    }

                    item.isEnabled = true
                })
    }

```

This example demonstrates how to use **GEMKit** in a SwiftUI application to calculate a car route between two coordinates and display it on the map with a summary panel.

Check the full implementation on [GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/SwiftUI/RoutesAndNavigation/CalculateRoute).

![Calculated Route with Insets](/docs/ios/assets/images/example_ios_calculate_route-90cb529a0245c53736ddd852bc4535ab.png)

**Calculated Route with Insets**

### Map View and Route Display[​](#map-view-and-route-display "Direct link to Map View and Route Display")

The map is displayed using `MapBase` with a declarative `MapRoute` child that automatically re-renders whenever `calculatedRoutes` changes:

ContentView\.swift[View on GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/SwiftUI/RoutesAndNavigation/CalculateRoute/CalculateRoute/ContentView.swift)

```swift
struct ContentView: View {
    @State private var navigationContext: NavigationContext?
    @State private var trafficContext: TrafficContext?
    @State private var isCalculating: Bool = false
    @State private var edgeInsets: UIEdgeInsets?
    @State private var calculatedRoutes: [RouteObject] = []

    var body: some View {
        MapReader { proxy in
            ZStack {
                MapBase {
                    MapRoute(
                        routes: calculatedRoutes,
                        traffic: trafficContext,
                        animationDuration: 800
                    )
                }
                .ignoresSafeArea(edges: [.bottom, .horizontal])

                // visually indicate the edge area padding after route is presented
                if let insets = edgeInsets {
                    EdgeAreaOverlay(insets: insets)
                        .ignoresSafeArea(edges: [.bottom, .horizontal])
                        .allowsHitTesting(false)
                }
            }
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("", systemImage: "point.topleft.down.curvedto.point.bottomright.up") {
                        calculateRoute(proxy)
                    }
                    .disabled(isCalculating)
                    .buttonStyle(.borderedProminent)
                }
                ToolbarItem(placement: .topBarTrailing) {
                    Button("", systemImage: "clear") {
                        clearRoute(proxy)
                    }
                    .buttonStyle(.borderedProminent)
                }
            }
        }
        .navigationTitle("Calculate Route")
        .navigationBarTitleDisplayMode(.inline)
    }

```

### Setting Route Preferences and Calculating[​](#setting-route-preferences-and-calculating-1 "Direct link to Setting Route Preferences and Calculating")

Route preferences are configured on a `RoutePreferencesObject` and passed to a `NavigationContext`. Edge area insets are applied to ensure the route summary fits within the visible map area:

ContentView\.swift[View on GitHub](https://github.com/magiclane/magiclane-maps-sdk-examples-for-ios/tree/main/SwiftUI/RoutesAndNavigation/CalculateRoute/CalculateRoute/ContentView.swift)

```swift
    func calculateRoute(_ proxy: MapProxy) {

        guard let mapViewController = proxy.mapViewController else { return }

        if navigationContext == nil {

            let preferences = RoutePreferencesObject()
            preferences.setTransportMode(.car)
            preferences.setRouteType(.fastest)
            preferences.setAvoidMotorways(false)
            preferences.setAvoidTollRoads(false)
            preferences.setAvoidFerries(false)
            preferences.setAvoidUnpavedRoads(true)

            navigationContext = NavigationContext(preferences: preferences)
        }

        if trafficContext == nil {

            trafficContext = TrafficContext()
            trafficContext?.setUseTraffic(.useOnline)
        }

        let waypoints = [
            LandmarkObject.landmark(
                withName: "San Francisco",
                location: CoordinatesObject.coordinates(withLatitude: 37.77903, longitude: -122.41991)),
            LandmarkObject.landmark(
                withName: "San Jose",
                location: CoordinatesObject.coordinates(withLatitude: 37.33619, longitude: -121.89058))
        ]

        isCalculating = true

        navigationContext?.calculateRoute(withWaypoints: waypoints, completionHandler: { results in

            if !results.isEmpty {

                let scale = UIScreen.main.scale
                let insets = UIEdgeInsets(
                    top: 120 * scale, left: 70 * scale,
                    bottom: 70 * scale, right: 70 * scale)

                edgeInsets = insets

                mapViewController.setEdgeAreaInsets(insets)
                mapViewController.presentRoutes(results, withTraffic: trafficContext, showSummary: true, animationDuration: 1600)

                calculatedRoutes = results
            }

            isCalculating = false
        })
    }

```
