Trying to display location data from Firebase to MapKit

不羁岁月 提交于 2019-12-10 11:58:36

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/51448696/trying-to-display-location-data-from-firebase-to-mapkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!