Belo
Belo

Reputation: 21

Trying to display location data from Firebase to MapKit

searched about this question a lot but couldn't find a simple answer.

I want to be able to read location data from a Firebase database and display them on the MapKit as annotation.

Can you help?

Right now I can display annotations that are hard-coded but can't figure out how to read the database and then create a loop that displays all annotations on the map.

This is the code for showing the annotations. I want to fill title, latitude, longitude with the relevant data from Firebase. The Firebase database is as follows: Firebase Database

**The application is already connected with the Firebase!

let points = [
        ["title": ,    "latitude": , "longitude": ],    
    ]
    for point in points {
        let annotation = MKPointAnnotation()
        annotation.title = point["title"] as? String
        annotation.coordinate = CLLocationCoordinate2D(latitude: point["latitude"] as! Double, longitude: point["longitude"] as! Double)
        mapView.addAnnotation(annotation)
    }

After suggestion I edited the code and it is like this right now:

let ref = Database.database().reference()
    ref.child("x-database-alpha/name").observe(.childAdded, with: { (snapshot) in

        let title = (snapshot.value as AnyObject?)!["Title"] as! String?
        let latitude = (snapshot.value as AnyObject?)!["Latitude"] as! String?
        let longitude = (snapshot.value as AnyObject?)!["Longitude"] as! String?

        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
        annotation.title = title
        self.mapView.addAnnotation(annotation)
    })

Check theExact Firebase Database

Right now the code has no error but it doesn't present the annotation!

Upvotes: 0

Views: 715

Answers (1)

Kosuke Ogawa
Kosuke Ogawa

Reputation: 7451

Sample code:

let ref = Database.database().reference()
ref.child("name").observe(.childAdded, with: { (snapshot) in

let title = (snapshot.value as AnyObject!)!["Title"] as! String!
let latitude = (snapshot.value as AnyObject!)!["Latitude"] as! String!
let longitude = (snapshot.value as AnyObject!)!["Longitude"] as! String!

let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
annotation.title = title
self.map.addAnnotation(annotation)
})

Upvotes: 0

Related Questions