我想在单击
Marker
或 Annotation
上的 Map
时显示一张表格,显示有关位置的相关信息。我发现关于如何在 SwiftUI 中执行此操作的资源为零,尽管它在许多使用地图的应用程序中是相当标准的行为。我尝试向 Marker
添加点击手势,但 SwiftUI 不允许这样做。
onTapGesture
与 Annotation
配合使用,因为您可以将自定义 View
作为 content
。
import SwiftUI
import MapKit
struct SelectedMapSample: View {
@State private var selectedCoordinate: CLLocationCoordinate2D?
@State private var coordinates = (0...100).map { _ in
CLLocationCoordinate2D.random()
}
var body: some View {
Map(position: .constant(.automatic)){
ForEach($coordinates) { $coordinate in
Annotation(coordinate.description, coordinate: coordinate) {
Text(coordinate.description)
.onTapGesture {
selectedCoordinate = coordinate
print("tapped\n\t \(coordinate.description)")
}
}
}
}
.sheet(item: $selectedCoordinate) { coordinate in
Text(coordinate.description)
.presentationDetents([.fraction(0.3)])
.presentationBackgroundInteraction(.enabled(upThrough: .fraction(0.3)))
}
}
}
#Preview {
SelectedMapSample()
}
extension CLLocationCoordinate2D {
static func random() -> CLLocationCoordinate2D {
let latitude = Array(stride(from: -90, through: 90, by: 0.5)).randomElement()!
let longitude = Array(stride(from: -180, through: 180, by: 0.5)).randomElement()!
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
extension CLLocationCoordinate2D: @retroactive Identifiable {
public var id: String {
description
}
public var description: String{
"latitude: \(latitude)\nlongitude: \(longitude)"
}
}