Zum Inhalt

User Location (iOS)

Zeigt den aktuellen Standort des Benutzers auf der Karte an.

MapSession erforderlich

Denken Sie daran, die MapSession in Ihre App zu integrieren. Die MapSession muss alle 10 Minuten aufgerufen werden, solange die Karte aktiv ist.

Info.plist

Fügen Sie Ihrer Info.plist den folgenden Schlüssel hinzu:

<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
            }
    }
}