在 swiftUI 2 中向 MapKit 添加 MapMarker

adding a MapMarker to MapKit in swiftUI 2

我正在尝试使用新的 Mapkit SwiftUI view and I am able to show a map with a certain region but I can't figure how to show a Map Marker

这是我的:

import SwiftUI
import MapKit

struct ContentView: View {
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
    var location1 =  MapMarker(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), tint: .red)
    
    
    var body: some View {
        Map(coordinateRegion: $region, showsUserLocation: true).edgesIgnoringSafeArea(.all)
    }
}

有人知道如何将 location1 添加到地图吗?我找到了 this 但我无法让它工作

这是一个简单的演示。用 Xcode 12 / iOS 14

测试

import CoreLocation
import MapKit

struct Marker: Identifiable {
    let id = UUID()
    var location: MapMarker
}

struct DemoView: View {

    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))

    let markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), tint: .red))]


    var body: some View {
        Map(coordinateRegion: $region, showsUserLocation: true, 
          annotationItems: markers) { marker in
            marker.location
        }.edgesIgnoringSafeArea(.all)
    }
}

backup

您可以使用 MapPin() 或 MapMarker() 如下:

import SwiftUI
import MapKit

struct Place: Identifiable {
let id = UUID()
let name: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
    CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
  }
}

struct MapView: View {

let places = [
    Place(name: "Position 1", latitude: 31.21, longitude: 120.50),
    Place(name: "Position 2", latitude: 31.210205, longitude: 120.52301),
    Place(name: "Position 3", latitude: 31.230006, longitude: 120.54002)
]

@State private var region = MKCoordinateRegion(
    center: CLLocationCoordinate2D(latitude: 31.21, longitude: 120.50),
    span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)

var body: some View {
    Map(coordinateRegion: $region, showsUserLocation: false,  annotationItems: places){ place in
        MapPin(coordinate: place.coordinate)
        //MapMarker(coordinate: place.coordinate)

    }
  }
}