SwiftUI地图显示注释 [英] SwiftUI Map Display Annotations
问题描述
我决定从将MKMapView包装到UIViewRepresentable中切换为SwiftUI中的新Map()
.
I decided to switch from wrapping MKMapView into a UIViewRepresentable to the new Map()
in SwiftUI.
我可以在Map()
中正确显示一个MKMapRect
,但是在此我无法显示两个MKPointAnnotation
.而且我在这些注释之间的路线没有显示
I was able to display correctly a MKMapRect
into the Map()
but I am unable to display two MKPointAnnotation
there. Also my route between these annotation is not showing
它要求我提供一个RandomAccessCollection
和(Identifiable) -> MapAnnotationProtocol>
,但我不知道该放在哪里.
It is requiring me to provide an RandomAccessCollection
and a (Identifiable) -> MapAnnotationProtocol>
but I do not know what to put there.
任何想法我应该在(Identifiable) -> MapAnnotationProtocol
中放入什么?
Any idea what should I put in (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
的结构:
You don't need to do MKPointAnnotation
anymore. Currently, in Xcode 12.0 Beta, there are three structs that SwiftUI provides to satisfy the MapAnnotationProtocol
:
-
MapAnnotation
-
MapMarker
-
MapPin
MapAnnotation
MapMarker
MapPin
RandomAccessCollection
应该是采用Identifiable
的对象的任何集合(将执行数组操作).这些在Map
初始化程序的最终参数中用作块的参数.
The RandomAccessCollection
should be any collection (an array will do) of objects that adopt Identifiable
. These used as the argument of the block in the final argument of the Map
initializer.
Map(coordinateRegion: $container.region,
annotationItems: container.annotationLocations) {
(location) -> MapPin in
MapPin(coordinate: location.coordinate)
})
这篇关于SwiftUI地图显示注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!