ios - SwiftUI:如何在地图上显示多个图钉?
问题描述
所以我目前有这段代码,它显示了一个带有大头针的地图。
但我想知道如何显示多个别针而不仅仅是一个,还显示用户当前位置,所以如果用户移动“点”也应该移动
如果用户点击图钉,我想在控制台上打印一些东西
struct GeoPointView : View {
var position : GeoPoint
struct IdentifiablePoint: Identifiable {
var id = UUID()
var position : GeoPoint
}
var body: some View {
Map(coordinateRegion: .constant(
MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: position.latitude, longitude: position.longitude), span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))), annotationItems: [position].map { IdentifiablePoint(position: $0)}) { point in
MapPin(coordinate: CLLocationCoordinate2D(latitude: point.position.latitude, longitude: point.position.longitude))
}
.cornerRadius(10)
}
}
解决方案
要显示多个点,您需要一个GeoPoint
s 数组。
然后,您可能希望对地图的居中/缩放位置进行一些合理化以查看所有点。我已将其包含在我的centerOfPoints
计算属性中。
struct GeoPointView : View {
var positions : [GeoPoint]
struct IdentifiablePoint: Identifiable {
var id = UUID()
var position : GeoPoint
}
var centerOfPoints : (center: CLLocationCoordinate2D, span: MKCoordinateSpan) {
var minLat = 91.0
var maxLat = -91.0
var minLon = 181.0
var maxLon = -181.0
for i in positions {
maxLat = max(maxLat, i.latitude)
minLat = min(minLat, i.latitude)
maxLon = max(maxLon, i.longitude)
minLon = min(minLon, i.longitude)
}
let center = CLLocationCoordinate2D(latitude: (maxLat + minLat) / 2,
longitude: (maxLon + minLon) / 2)
let span = MKCoordinateSpan(latitudeDelta: abs(maxLat - minLat) * 1.3,
longitudeDelta: abs(maxLon - minLon) * 1.3)
return (center: center,
span: span)
}
var body: some View {
let center = centerOfPoints
return Map(coordinateRegion: .constant(MKCoordinateRegion(center: center.center, span: center.span)), showsUserLocation: true, annotationItems: positions.map { IdentifiablePoint(position: $0)}) { (point) in
MapPin(coordinate: CLLocationCoordinate2D(latitude: point.position.latitude,
longitude: point.position.longitude))
}
}
}
你可以这样称呼它:
GeoPointView(positions: [GeoPoint(latitude: 43.0, longitude: -75),
GeoPoint(latitude: 41.0, longitude: -75),
GeoPoint(latitude: 41.0, longitude: -85),
])
我showsUserLocation: true
在地图上添加了一个以显示用户位置的蓝点。请注意,这需要额外的设置,添加到您的 Info.plist 并请求访问位置数据的权限。https://fluffy.es/current-location/似乎是其中一些合理的教程。如果您需要额外的帮助来设置权限,我建议将其拆分为另一个问题,因为这个问题的范围已经很大。
我没有看到可用于判断是否已点击地图图钉的 API,尽管也许其他人会提供有关此信息的信息。
推荐阅读
- java - 无法下载 Maven 依赖项 - AnypointStudio
- r - 仅在指定因素之间连接 geom_line
- kotlin - 在 Kotlin 中将属性覆盖为常量的最佳方法
- php - 队列 Redis 不会在 Laravel Forge 上触发
- python - SCAPY 发送数据包错误 OSError: [Errno 97] 地址族不受协议支持
- c - 在C中没有循环的右数组移位
- php - 有没有办法在PHP中的十进制数的某个点之后进行正则表达式和删除?
- c# - 搜索文本并突出显示
- ruby-on-rails - Rails Action Cable:如何授权传入连接?
- javascript - Vuejs 组件之间的分离和通信