> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/ios/ja/maps/llms.txt)

# Display the user's location

![Display the user's location on a map with the default user location puck.](https://docs.mapbox.com/ios/ja/assets/ideal-img/maps-examples-tracking-mode.a024664.480.png)

This code demonstrates how to add a location button to a map using the **Mapbox Maps SDK for iOS**. The `ViewController` initializes a [`MapView`](https://docs.mapbox.com/ios/maps/api/latest/documentation/mapboxmaps/mapview/) with camera settings and style options and adds a button to toggle user location tracking. The location button dynamically updates the map's camera to center on the user's location when tracking is enabled by listening for the [`onLocationChange`](https://docs.mapbox.com/ios/maps/api/latest/documentation/mapboxmaps/locationmanager/onlocationchange/) observer.

Additionally, the example includes a button to toggle the visibility of a "bearing image" on the location puck and a `UISegmentedControl` for switching between map styles. Gesture interactions are handled to disable tracking when the user interacts with the map manually, ensuring a seamless and intuitive experience.

> **Note (warning): Troubleshooting with the iOS simulator**
> 
> If you cannot see the location puck while testing in the iOS simulator, try the following:
> 
> -   Simulate a location in Xcode by going to **Debug > Simulate Location** and select a location. Then, return to the Simulator and the location puck should appear over the selected location.
> -   If you already declined location permissions for your application you can update permission in Settings. Go to **Settings > Privacy & Security > Location Services**. Then find your application and update the location access to "Always" or "While Using the App".

> **Note: iOS Examples App Available**
> 
> This example code is part of the **Maps SDK for iOS Examples App**, a working iOS project [available on Github](https://github.com/mapbox/mapbox-maps-ios/tree/11.28.4/Sources/Examples). iOS developers are encouraged to run the examples app locally to interact with this example in an emulator and explore other features of the Maps SDK.
> 
> See our [Run the Maps SDK for iOS Examples App](https://docs.mapbox.com/help/tutorials/maps-sdk-ios-examples-app/) tutorial for step-by-step instructions.

**Swift**

Title: `TrackingModeExample.swift`

[View on GitHub](https://github.com/mapbox/mapbox-maps-ios/blob/main/Sources/Examples/All%20Examples/TrackingModeExample.swift)

```swift
import UIKit
import SwiftUI
import MapboxMaps

final class ViewController: UIViewController {
    private var locationTrackingCancellation: AnyCancelable?

    private var mapView: MapView!
    private var style: Style = .standard {
        didSet {
            mapView.mapboxMap.styleURI = style.uri
        }
    }
    private var showsBearingImage: Bool = false {
        didSet {
            let configuration = Puck2DConfiguration.makeDefault(showBearing: showsBearingImage)
            mapView.location.options.puckType = .puck2D(configuration)
        }
    }

    override public func viewDidLoad() {
        super.viewDidLoad()

        // Set initial camera settings
        let cameraOptions = CameraOptions(center: CLLocationCoordinate2D(latitude: 37.26301831966747, longitude: -121.97647612483807), zoom: 10)
        let options = MapInitOptions(cameraOptions: cameraOptions, styleURI: style.uri)

        mapView = MapView(frame: view.bounds, mapInitOptions: options)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(mapView)

        setupSettingsButton()

        // Add user position icon to the map with location indicator layer
        mapView.location.options.puckType = .puck2D()
        mapView.location.options.puckBearingEnabled = true

        mapView.gestures.delegate = self

        // Update the camera's centerCoordinate when a locationUpdate is received.
        startTracking()
    }

    public 

    private func setupSettingsButton() {
        let buttonView = SettingsButtonView(onTap: openSettings)
        let hostingController = UIHostingController(rootView: buttonView)
        hostingController.view.backgroundColor = .clear
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false

        addChild(hostingController)
        view.addSubview(hostingController.view)
        hostingController.didMove(toParent: self)

        NSLayoutConstraint.activate([
            hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            hostingController.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -120)
        ])
    }

    private func openSettings() {
        let controlsSection = SettingsSection(
            title: "Controls",
            controls: [
                .toggle(
                    title: "Track user location",
                    isOn: Binding(
                        get: { [weak self] in self?.locationTrackingCancellation != nil },
                        set: { [weak self] in $0 ? self?.startTracking() : self?.stopTracking() }
                    )
                ),
                .toggle(
                    title: "Show bearing image",
                    isOn: Binding(
                        get: { [weak self] in self?.showsBearingImage ?? false },
                        set: { [weak self] in self?.showsBearingImage = $0 }
                    )
                ),
                .segmentedPicker(
                    title: "Map style",
                    options: Style.allCases.map(\.name),
                    selection: Binding(
                        get: { [weak self] in self?.style.rawValue ?? 0 },
                        set: { [weak self] newValue in
                            self?.style = Style(rawValue: newValue) ?? .standard
                        }
                    )
                )
            ]
        )

        let docsSection = SettingsSection(
            title: "Docs",
            controls: [
                .link(
                    title: "Tracking mode example",
                    url: URL(string: "https://docs.mapbox.com/ios/maps/examples/tracking-mode/")!
                )
            ]
        )

        let settingsView = SettingsSheet(sections: [controlsSection, docsSection])
        let hostingController = UIHostingController(rootView: settingsView)

        if let sheet = hostingController.sheetPresentationController {
            sheet.detents = [.medium()]
            sheet.prefersGrabberVisible = true
        }

        present(hostingController, animated: true)
    }

    private func startTracking() {
        locationTrackingCancellation = mapView.location.onLocationChange.observe { [weak mapView] newLocation in
            guard let location = newLocation.last, let mapView else { return }
            mapView.camera.ease(
                to: CameraOptions(center: location.coordinate, zoom: 15),
                duration: 1.3)
        }
    }

    private func stopTracking() {
        locationTrackingCancellation = nil
    }
}

extension ViewController: GestureManagerDelegate {
    public func gestureManager(_ gestureManager: MapboxMaps.GestureManager, didBegin gestureType: MapboxMaps.GestureType) {
        stopTracking()
    }

    public func gestureManager(_ gestureManager: MapboxMaps.GestureManager, didEnd gestureType: MapboxMaps.GestureType, willAnimate: Bool) {}

    public func gestureManager(_ gestureManager: MapboxMaps.GestureManager, didEndAnimatingFor gestureType: MapboxMaps.GestureType) {}
}

extension ViewController {
    private enum Style: Int, CaseIterable {
        case standard
        case light
        case satelliteStreets
        case customUri

        var name: String {
            switch self {
            case .standard:
                return "Standard"
            case .light:
                return "Light"
            case .satelliteStreets:
                return "Satellite"
            case .customUri:
                return "Custom"
            }
        }

        var uri: StyleURI {
            switch self {
            case .standard:
                return .standard
            case .light:
                return .light
            case .satelliteStreets:
                return .satelliteStreets
            case .customUri:
                let localStyleURL = Bundle.main.url(forResource: "blueprint_style", withExtension: "json")!
                return .init(url: localStyleURL)!
            }
        }
    }
}

// MARK: - SwiftUI Settings Button
private struct SettingsButtonView: View {
    let onTap: () -> Void

    var body: some View {
        Button(action: onTap) {
            Image(systemName: "slider.horizontal.3")
        }
        .buttonStyle(MapFloatingButtonStyle())
    }
}
```