Skip to content

User Location (iOS)

Display the user's current location on the map.

MapSession required

Remember to integrate the MapSession in your app. The MapSession must be called periodically every 10 minutes while the map is active.

Info.plist

Add the following key to your Info.plist:

<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to show it on the map.</string>

UIKit

import UIKit
import MapLibre

class UserLocationViewController: UIViewController, MLNMapViewDelegate {
    private var mapView: MLNMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let styleURL = URL(string:
            "https://tiles.smartmaps.cloud/styles/v1/smartmaps/light/style.json?apiKey=[INSERT API-KEY]&channel=app"
        )!

        mapView = MLNMapView(frame: view.bounds, styleURL: styleURL)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.delegate = self

        // Enable user location
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow

        view.addSubview(mapView)
    }

    func mapView(_ mapView: MLNMapView, didUpdate userLocation: MLNUserLocation?) {
        guard let location = userLocation?.coordinate else { return }
        mapView.setCenter(location, zoomLevel: 14, animated: true)
    }
}

SwiftUI

import SwiftUI
import MapLibre
import MapLibreSwiftUI

struct UserLocationMapView: View {
    let styleURL = URL(string:
        "https://tiles.smartmaps.cloud/styles/v1/smartmaps/light/style.json?apiKey=[INSERT API-KEY]&channel=app"
    )!

    var body: some View {
        MapView(styleURL: styleURL)
            .mapViewModifier { mapView in
                mapView.showsUserLocation = true
                mapView.userTrackingMode = .follow
            }
    }
}