尝试显示从Firebase到MapKit的位置数据 [英] Trying to display location data from Firebase to MapKit
问题描述
对此问题进行了很多搜索,但找不到简单的答案.
searched about this question a lot but couldn't find a simple answer.
我希望能够从Firebase数据库读取位置数据并将其作为注释显示在MapKit上.
I want to be able to read location data from a Firebase database and display them on the MapKit as annotation.
你能帮忙吗?
现在,我可以显示经过硬编码但不能弄清楚如何读取数据库的注释,然后创建一个循环,在地图上显示所有注释.
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.
这是显示注释的代码. 我想用Firebase中的相关数据填充标题,纬度,经度. Firebase数据库如下: Firebase数据库
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
**该应用程序已与Firebase连接!
**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)
})
现在代码没有错误,但是没有注释!
Right now the code has no error but it doesn't present the annotation!
推荐答案
示例代码:
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)
})
这篇关于尝试显示从Firebase到MapKit的位置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!