来自 Binding SwiftUI 的 MapMarker

MapMarker from Binding SwiftUI

我正在尝试根据 selectedBus var 的经度和纬度在地图上显示地图标记,但我无法解决它。

使用以下代码我收到错误静态方法 'buildBlock' 要求 'MapMarker' 符合 'View'

import SwiftUI
import MapKit
import CoreLocation

struct BusView: View {
    @Binding var selectedBus : Bus
    @State private var coordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 28), span: MKCoordinateSpan(latitudeDelta: 50, longitudeDelta: 50))

       var body: some View {
           Map(coordinateRegion: $coordinateRegion)
           MapMarker(coordinate: CLLocationCoordinate2D(latitude: selectedBus.location?.latitude ?? 0, longitude: selectedBus.location?.longitude ?? 0), tint: .red)
           
       }
}



    struct Bus: Decodable, Hashable {
    let remainingTime: Int?
    let plate: String?
    let routeCode: String?
    let icon: String?
    let location: Location?
}

struct Location: Decodable, Hashable {
    
    let latitude: Double?
    let longitude: Double?
}

您需要有一组注释(我刚刚调用的是 annotations)才能使用 MapMarker,因为那只是显示注释位置的 View。您的 var body 应如下所示:

   var body: some View {
    Map(coordinateRegion: $coordinateRegion, annotationItems: annotations) {
       MapMarker(coordinate: CLLocationCoordinate2D(latitude: selectedBus.location?.latitude ?? 0, longitude: selectedBus.location?.longitude ?? 0), tint: .red)
       }
   }