首页 > 解决方案 > 如何使用 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 中显示杂志的图像。帮助请

标签: swiftfirebasefirebase-realtime-databasemapkit

解决方案


创建一个自定义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
}

推荐阅读