Nick
Nick

Reputation: 219

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.

How can I then iterate over all of the Image Docs and get the 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?

enter image description here

Upvotes: 0

Views: 905

Answers (1)

jnpdx
jnpdx

Reputation: 52515

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)")
}

Update for displaying the 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

Upvotes: 2

Related Questions