swift - 如何使用 Firebase 添加注释图像(mapView)?
问题描述
我有这个func
用于填充引脚mapView
:
func obervePins(){
let magRef = Database.database().reference().child("map")
magRef.observe(.value) { (snapshot) in
//var tempCoord = [CoordinatesOfMagazine]()
for child in snapshot.children {
if let chidSnapshot = child as? DataSnapshot,
let dictMag = chidSnapshot.value as? [String: Any],
let title = dictMag["Title"] as? String,
let latitude = dictMag["Latitude"] as? String,
let longitude = dictMag["Longitude"] as? String {
// let imageOfMagazine = dictMag["imageOfMagazine"] as? String,
// let url = URL(string: imageOfMagazine) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: Double(latitude)!, longitude: Double(longitude)!)
annotation.title = title
print(annotation)
self.mapView.addAnnotations([annotation])
// let coordinates = CoordinatesOfMagazine(imageOfMagazine: url, Title: title)
// tempCoord.append(coordinates)
}
}
//self.coordinates = tempCoord
}
}
我在 Firebase 中的数据如下所示:
mapView 中的引脚是正确的。我不知道,如何在 mapView 中显示杂志的图像。帮助请
解决方案
创建一个自定义MKAnnotation
类。
class ImageAnnotation : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
var imageOfMagazine: String?
override init() {
self.coordinate = CLLocationCoordinate2D()
self.title = nil
self.subtitle = nil
self.imageOfMagazine = nil
}
}
设置数据并将注释添加到您的 mapView。
let annotation = ImageAnnotation()
annotation.coordinate = coordinate1
annotation.title = "title"
annotation.subtitle = "subtitle"
annotation.imageOfMagazine = imageOfMagazine
self.mapView.addAnnotation(annotation)
实现mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation)
委托方法。
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? ImageAnnotation else {
return nil
}
let reuseId = "Pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if pinView == nil {
pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.canShowCallout = true
let data = NSData(contentsOf: URL(string: annotation.imageOfMagazine!)!)
pinView?.image = UIImage(data: data! as Data)
}
else {
pinView?.annotation = annotation
}
return pinView
}
推荐阅读
- android - 逆向工程 BLE 设备 - 校验和?
- android - 单击外部时如何关闭Android对话框(使用FLAG_NOT_FOCUSABLE)
- java - 如何编译一个java项目来获取一个.jar文件
- postgresql - Postgres:忽略级联删除的 DELETE 触发器
- python-3.x - 如果您使用 AttributesToGet 参数在 DynamoDB 上运行扫描,您需要为每个项目的数据足迹付费还是只为请求的属性付费?
- python - 子进程中的 Sox 未创建输出文件
- javascript - NodeJS 似乎并行执行 2 次对同一个函数的调用
- stata - 如何在Stata中创建均值条形图?
- c - 在 ubuntu 上安装 clang 3.4 和 LLVM 3.4
- javascript - 以对角线方向更改对象的方向