SwiftUI 如何在地图 Map 视图中显示注释?

18 min read

要在地图 Map 视图中显示注释,您可以像以下代码样例一样,使用 MapAnnotation 的内容视图添加注释。这个示例在地图上添加了一个标记和注释:

import MapKit
import SwiftUI

struct MapView: View {
    
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.5154, longitude: -122.056),
        span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    )
    
    var body: some View {
        Map(coordinateRegion: $region, annotationItems: [annotation]) {
            MapAnnotation(coordinate: $0.coordinate) {
                VStack {
                    Image(systemName: "mappin.circle.fill")
                        .foregroundColor(.red)
                        .font(.title)
                    Text("My favorite place")
                }
            }
        }
    }
    
    var annotation: MKPointAnnotation {
        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 37.5154, longitude: -122.056)
        return annotation
    }
}

在上述代码中,Map 视图使用 MapAnnotation(coordinate:content:) 为注释提供坐标和内容视图。在这里,内容视图是一个垂直堆栈,其中包含一个图像和一个文本标签。图像是一个红色的地图钉,对应于 MapKit 中的 MKPointAnnotation。该坐标设置为 annotation 变量。