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