简体   繁体   English

SwiftUI:如何从 Cloud Firestore 获取 GeoPoint 并显示它?

[英]SwiftUI: How to fetch GeoPoint from Cloud Firestore and display it?

So I have this Cloud Firestore Setup, where each of the Image Documents have the same 4 fields, but with different values.所以我有这个 Cloud Firestore 设置,其中每个图像文档都有相同的 4 个字段,但具有不同的值。

How can I then iterate over all of the Image Docs and get the GeoPint?然后如何遍历所有图像文档并获取 GeoPint? So I later can display the Latitude and Longitude?所以我以后可以显示纬度和经度吗?

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?我猜迭代部分并不那么重要,所以另一种提问方式是,我怎样才能获得 Geopoint,然后在我的项目中显示它?

在此处输入图像描述

Building on my last answer ( https://stackoverflow.com/a/66377922/560942 ):基于我的最后一个答案( 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)")
}

Update for displaying the GeoPoint :显示 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)
    }
}

Usage:用法:

ForEach(images, id: \.id) { image in 
  Text("Location: \(image.position.latitude), \(image.position.longitude)")
  GeoPointView(position: image.position)
}

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如果您指的是 map,我可以根据需要更新此答案,或者您可以参考 Apple 开发者论坛上的以下帖子: https://developer.apple.com/forums/thread/651668

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM