swiftui - 使用 Pin 将坐标传输到 MapView
问题描述
我正在尝试在地图上显示地图图钉。输入交易后,详细信息与位置坐标一起保存。在交易条目列表中,用户可以单击条目以获取更多详细信息,包括显示交易位置的小地图。
根据Asperi 在 swiftUI 2 中向 MapKit 添加 MapMarker的建议,看来我需要声明一个可识别的结构才能使用地图图钉。
在 DetailView 中,纬度和经度在传输到 MapView 之前被复制到坐标参数。
struct DetailView: View {
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(
latitude: item.entryLat,
longitude: item.entryLong)
}
var body: some View {
VStack {
MapView(coordinate: coordinate)
.ignoresSafeArea(edges: .all)
.frame(height: 400)
.padding(.vertical, 10)
}
}
}
MapView 是我遇到麻烦的地方。我不确定如何传入我的区域坐标和标记(xxxxx)。将坐标复制到@State 区域,标记会产生错误“传递给不带参数的调用的参数”。
struct Marker: Identifiable {
let id = UUID()
var location: MapMarker
}
struct MapView: View {
var coordinate: CLLocationCoordinate2D
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(xxxxxxx), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
let markers = [Marker(location: MapMarker(coordinate: CLLocationCoordinate2D(xxxxxxx), tint: .red))]
var body: some View {
Map(coordinateRegion: $region, showsUserLocation: true,
annotationItems: markers) { marker in
marker.location
}.edgesIgnoringSafeArea(.all)
}
}
解决方案
听起来对于您的应用程序来说,将区域声明为常量将起作用。代码如下所示:
struct Marker: Identifiable {
let id = UUID()
var location: MapMarker
}
struct MapView: View {
var coordinate: CLLocationCoordinate2D
var body: some View {
Map(coordinateRegion: .constant(MKCoordinateRegion(center: coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))),
showsUserLocation: true,
annotationItems: [Marker(location: MapMarker(coordinate: coordinate))]) { marker in
marker.location
}.edgesIgnoringSafeArea(.all)
}
}
如果您仍想将其用作 @State 变量,则可以使用自定义init
来设置值:
struct MapView: View {
var coordinate: CLLocationCoordinate2D
@State private var region : MKCoordinateRegion
init(coordinate : CLLocationCoordinate2D) {
self.coordinate = coordinate
_region = State(initialValue: MKCoordinateRegion(center: coordinate,
span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)))
}
var body: some View {
Map(coordinateRegion: $region,
showsUserLocation: true,
annotationItems: [Marker(location: MapMarker(coordinate: coordinate))]) { marker in
marker.location
}
.edgesIgnoringSafeArea(.all)
}
}
最后,我定义了内联标记数组,但您可以将其拆分为计算属性:
var markers : [Marker] {
[Marker(location: MapMarker(coordinate: coordinate))]
}
var body: some View {
Map(coordinateRegion: $region,
showsUserLocation: true,
annotationItems: markers) { marker in
marker.location
}
.edgesIgnoringSafeArea(.all)
}
推荐阅读
- solr - 为什么 *:* 与 (*:*) 产生不同的结果?
- r - 带有已处理警告的 tryCatch 直通
- mysql - 我无法在 Laravel 中禁用“ONLY_FULL_GROUP_BY”模式
- if-statement - 如何申请macroin sas?
- java - 我们可以从 UncategorizedSQLException 中恢复吗?
- azure-data-factory - 如何对基于 Azure 数据工厂的管道进行冒烟测试
- java - dockerBuild 失败导致不支持的类文件主要版本 61 错误
- c++ - 参数相关查找如何在搜索点之后找到声明?
- woocommerce - WooCommerce 检查购物车的优惠券
- c# - 我有一个位数不确定的bool数组,如何将它转换成一个短数组,每个bool值是一个位