SwiftUI:如何从Cloud Firestore获取GeoPoint并显示它?
所以我有这个Cloud Firestore设置,其中每个图像文档都有相同的4个字段,但是具有不同的值.
So I have this Cloud Firestore Setup, where each of the Image Documents have the same 4 fields, but with different values.
然后如何遍历所有图像文档并获得GeoPint?这样我以后可以显示纬度和经度吗?
How can I then iterate over all of the Image Docs and get the GeoPint? So I later can display the Latitude and Longitude?
我猜迭代部分并不重要,所以另一种询问方式是,如何获取Geopoint,然后将其显示在我的项目中?
I Guess the iteration part isn’t THAT important, so antoher way of asking is, how can I get the Geopoint and then display it in my project?
以我的最后一个答案为基础( https://stackoverflow.com/a/66377922/560942 ):
Building on my last answer (https://stackoverflow.com/a/66377922/560942):
struct ImageModel {
var id = UUID()
var quote : String
var url: String
var position: GeoPoint
}
images = snapshot.documents.compactMap { documentSnapshot -> ImageModel? in
let documentData = documentSnapshot.data()
if let quote = documentData["Quote"] as? String,
let url = documentData["Url"] as? String,
let position = documentData["Position"] as? GeoPoint
{
return ImageModel(quote: quote, url: url, position: position)
} else {
return nil
}
}
然后,稍后显示文本坐标:
Then, to display the text coordinates later on:
ForEach(images, id: \.id) { image in
Text("Location: \(image.position.latitude), \(image.position.longitude)")
}
更新以显示GeoPoint :
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.005, longitudeDelta: 0.005))), annotationItems: [position].map { IdentifiablePoint(position: $0)}) { point in
MapPin(coordinate: CLLocationCoordinate2D(latitude: point.position.latitude, longitude: point.position.longitude))
}
.frame(width: 200, height: 200)
}
}
用法:
ForEach(images, id: \.id) { image in
Text("Location: \(image.position.latitude), \(image.position.longitude)")
GeoPointView(position: image.position)
}
如果您要在地图上指的是我,可以根据需要更新此答案,也可以参考Apple开发者论坛上的以下帖子:
In the event you mean on a map, I can update this answer if needed, or you can refer to the following post on the Apple Developer Forums: https://developer.apple.com/forums/thread/651668