SwiftUI地图显示注释 [英] SwiftUI Map Display Annotations

查看:87
本文介绍了SwiftUI地图显示注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定从将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆