搜索了很多这个问题,但是找不到简单的答案。
我希望能够从Firebase数据库读取位置数据,并将其作为注释显示在MapKit上。
你能帮忙吗?
现在,我可以显示经过硬编码但无法弄清楚如何读取数据库的注释,然后创建一个循环,以在地图上显示所有注释。
这是显示注释的代码。 我想用Firebase中的相关数据填充标题,纬度,经度。 Firebase数据库如下:Firebase Database
**该应用程序已与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)
}
在提出建议后,我编辑了代码,现在就像这样:
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)
})
现在代码没有错误,但是没有注释!
答案 0 :(得分:0)
示例代码:
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)
})