Map in SwiftUI just wont follows users heading when first shown

I want to use a Map to show current location and heading, but the map first show, it just wont work. And when I switch off and switch on again, it works. codes below:

BackgroundMapView.swift

import SwiftUI
import MapKit

struct BackgroundMapView: View {
    
    var scope: Namespace.ID?
    
    private var cameraPosition: MapCameraPosition = .userLocation(
        followsHeading: true,
        fallback: .automatic
    )
    
    private var locations: [Location]
    
    init(_ scope: Namespace.ID? = nil, locations: [Location]) {
        self.scope = scope
        self.locations = locations
    }
    
    var body: some View {
        Map(
            initialPosition: cameraPosition,
            scope: scope
        ) {
            MapPolyline(coordinates: locations.map({ $0.coordinate.toGCJ02 }))
                .stroke(
                    .red,
                    lineWidth: 3
                )
        }
        .mapControlVisibility(.hidden)
    }
    
}

#Preview {
    MainView()
}

HomeVIew.swift

import SwiftUI

struct HomeView: View {
    
    @StateObject private var locationManager = LocationManager()
    
    @State private var isMapEnabled = UserDefaults.isHomeMapEnabled {
        didSet {
            UserDefaults.isHomeMapEnabled = isMapEnabled
        }
    }
    
    @Namespace private var mapScope
    
    var body: some View {
        if isMapEnabled {
            BackgroundMapView(mapScope, locations: locationManager.locations)
                .mapScope(mapScope)
        }
    }
}

I feel the pain. Here's what I've done to get the map oriented correctly the first time. First of all, you should introduce a @State....

@State private var position: MapCameraPosition = .automatic

Then initialize the Map with a binding to the @State like this....

Map(position: $position) {

The final piece is to add a .task view modifier to Map...

.task {
   position = .userLocation(followsHeading: true, fallback: .automatic)
 }

What this does is execute the statements at a slightly later time on the MainActor after the view appears. Apparently, the heading-following functionality isn't ready on initialization of BackgroundMapView or Map. By the time the Task completes, the app seems prepared and do the right thing.

So your code should look something like this:

@State private var position: MapCameraPosition = .automatic

var body: some View {
   Map(position: $position) {
      // ....
   }
   .task {
      position = .userLocation(followsHeading: true, fallback: .automatic)
   }   
}

Hope this works out.

Map in SwiftUI just wont follows users heading when first shown
 
 
Q