I created the function getAnnotations
and I get no errors when calling that function inside of my view, or even when I define the function, but the Map
gets 2 error:
Initializer 'init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)' requires that 'MKPointAnnotation.Type.Element' conform to 'Identifiable'
and
Type 'MKPointAnnotation.Type' cannot conform to 'RandomAccessCollection'
Code for the function getAnnotations
:
func getAnnotations(completion: @escaping (_ annotations: [MKPointAnnotation]?) -> Void) {
let db = Firestore.firestore()
db.collection("annotations").addSnapshotListener { (querySnapshot, err) in
guard let snapshot = querySnapshot else {
if let err = err {
print(err)
}
completion(nil) // return nil if error
return
}
guard !snapshot.isEmpty else {
completion([]) // return empty if no documents
return
}
var annotations = [MKPointAnnotation]()
for doc in snapshot.documents {
if let lat = doc.get("lat") as? String,
let lon = doc.get("long") as? String,
let latitude = Double(lat),
let longitude = Double(lon) {
let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let annotation = MKPointAnnotation()
annotation.coordinate = coord
annotations.append(annotation)
}
}
completion(annotations) // return array
}
}
And my view:
ZStack (alignment: .bottom) {
Map(coordinateRegion: $viewModel.region,
showsUserLocation: true, annotationItems: MKPointAnnotation) { annotations in
MapAnnotation(coordinate: annotations.coordinate) {
Circle()
}
}
.ignoresSafeArea()
.tint(.pink)
LocationButton(.currentLocation) {
viewModel.requestAllowOnceLocationPermission()
}
.foregroundColor(.white)
.cornerRadius(8)
.labelStyle(.iconOnly)
.symbolVariant(.fill)
.tint(.pink)
.padding(.bottom)
.padding(.trailing, 300)
}
.onAppear {
getAnnotations({ (annotations) in
if let annotations = annotations {
print(annotations)
}
})
}
I tried to make this a synchronous function, but I'm still getting the 2 errors. Is it possible to resolve those first so I could see if my getAnnotations
function actually works or no?