我正在尝试创建我的第一个应用程序,它是一个允许我在比赛和训练模式下跟踪我的耐力赛(越野车)课程进度的应用程序,碰巧我的应用程序必须具备的基本功能之一是地图上的跟踪系统,以便保存我的路线。我正在尝试在我的应用程序中实现地图,但发现了几个错误,如果格式或我在这里编写的任何内容不正确,我想道歉,这是我第一次在这里询问。 我使用的是 Xcode 15.4 和 iOS 17.5, 非常感谢您抽出时间。
import SwiftUI
import MapKit
struct IdentifiableCoordinate: Identifiable {
let id = UUID()
let coordinate: CLLocationCoordinate2D
}
struct SecondView: View {
@StateObject private var locationManager = LocationManager()
var body: some View {
ZStack {
Map(coordinateRegion: $locationManager.region, showsUserLocation: true, annotationItems: locationManager.trackingLocations) { location in ( here is the error message: Initializer 'init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)' requires that 'Annotation<Text, some View>' conform to 'MapAnnotationProtocol'
Annotation(location.coordinate, coordinate: <#CLLocationCoordinate2D#>) { ( here is the second error message: Initializer 'init(_:coordinate:anchor:content:)' requires that 'CLLocationCoordinate2D' conform to 'StringProtocol'
Circle()
.strokeBorder(Color.red, lineWidth: 2)
.frame(width: 30, height: 30)
}
}
.ignoresSafeArea()
.onAppear {
locationManager.checkIfLocationServicesIsEnabled()
}
VStack {
Text("ENDURapp")
.font(.largeTitle)
.foregroundColor(.white)
.padding(.top, 50)
Spacer()
}
}
}
}
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
@Published var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), // Coordenada inicial
span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
)
@Published var trackingLocations: [IdentifiableCoordinate] = []
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func checkIfLocationServicesIsEnabled() {
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
} else {
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.last else { return }
region = MKCoordinateRegion(
center: latestLocation.coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
)
trackingLocations.append(IdentifiableCoordinate(coordinate: latestLocation.coordinate))
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
我按照有人建议进行了以下更改:不要使用 ForEach 使用带有 Map 的注释项,但这也不起作用。
Annotation
替换为 MapAnnotation
代码将编译。如果您的目标低于 iOS 17,则必须使用较旧的已弃用类型。
有关如何使用 iOS 17.0+
Annotation
类型的示例,教程 将 MapKit 与 SwiftUI 集成 提供了非常好的介绍。
您共享的代码中还有其他几个问题。非详尽列表:
LocationManager
应作为 @State private var locationManager = LocationManager()
而不是状态对象CLLocationManager.locationServicesEnabled()
,例如if locationManager.authorizationStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}