我决定从包装 MKMapView 到 UIViewRepresentable 切换到新的 Map()
在 SwiftUI 中。
我能够正确显示 MKMapRect
进Map()
但我无法显示两个 MKPointAnnotation
那里。我的这些注释之间的路线也没有显示
它要求我提供 RandomAccessCollection
和一个 (Identifiable) -> MapAnnotationProtocol>
但我不知道该放什么。
知道我应该放什么 (Identifiable) -> MapAnnotationProtocol
?
import SwiftUI
import MapKit
extension MKPointAnnotation: Identifiable { }
struct ItemView: View {
@ObservedObject var itemViewModel: ItemViewModel
@State var coll = [MKPointAnnotation]()
func onAppear() {
let requestAnnotation = MKPointAnnotation()
requestAnnotation.coordinate = CLLocationCoordinate2D(latitude: 46.2004781, longitude: 6.1346497)
requestAnnotation.title = "Package"
let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.coordinate = CLLocationCoordinate2D(latitude: 47.1420446, longitude: 9.5204032)
destinationAnnotation.title = "Destination"
coll.append(requestAnnotation)
coll.append(destinationAnnotation)
}
var body: some View {
VStack {
if let mapRect = itemViewModel.route?.polyline.boundingMapRect {
Map(mapRect: .constant(mapRect), annotationItems: coll) { point in
MapAnnotation(coordinate: point.coordinate) {
Text(point.title ?? "")
}
}
}
}
.onAppear(perform: self.onAppear)
}
}
最佳答案
你不需要做MKPointAnnotation
了。目前,在 Xcode 12.0 Beta 中,SwiftUI 提供了三个结构体来满足 MapAnnotationProtocol
:
MapAnnotation
MapMarker
MapPin
RandomAccessCollection
应该是采用 Identifiable
的对象的任何集合(数组都可以) .这些在 Map
的最后一个参数中用作块的参数初始化程序。Map(coordinateRegion: $container.region,
annotationItems: container.annotationLocations) {
(location) -> MapPin in
MapPin(coordinate: location.coordinate)
})
关于ios - SwiftUI map 显示注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62543034/