如何在地图上显示基于图像的注释视图

How to show image-based annotation view on map

这是我的代码

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    @IBOutlet weak var mapView: MKMapView!
    let loc = [["Title": "Banglore",
                "Latitude": 12.9716,
                "longtitute": 77.5946,
                "SubTitle": "karnataka",
                "Detial": "This is our capital"],
               ["Title": "Mumbai",
                "Latitude": 19.0760,
                "longtitute": 72.8777,
                "SubTitle": "Mahrasthra",
                "Detial": "This is our capital"],
               ["Title": "Shimla",
                "Latitude": 31.1048,
                "longtitute": 77.1734,
                "SubTitle": "Himachal",
                "Detial": "This is our capital"]]

    override func viewDidLoad() {
        super.viewDidLoad()
        for location in loc {                
            let anaomtioView = MKAnnotationView()
            let annotaion = MKPointAnnotation()
            annotaion.title = location["Title"] as? String
            annotaion.subtitle = location["SubTitle"] as? String
            anaomtioView.image = UIImage(named: "rose")
            let locations = CLLocationCoordinate2D(latitude: location["Latitude"] as! Double, longitude: location["longtitute"] as! Double)
            annotaion.coordinate = locations
            mapView.addAnnotation(annotaion)
        }  
    }
}
     

您正在实例化您的 MKAnnotationView,但从未使用过它。但是无论如何,您都不应该自己实例化注释视图。让地图视图根据需要为您实例化它们。您需要做的就是定义您自己的注释视图 subclass,为您的地图注册它,然后您就完成了:

class RoseAnnotationView: MKAnnotationView {
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        image = UIImage(named: "rose")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后,在 viewDidLoad 中注册注释视图:

override func viewDidLoad() {
    super.viewDidLoad()

    mapView.register(RoseAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)

    for location in loc {
        let annotation = MKPointAnnotation()
        annotation.title = ...
        annotation.subtitle = ...
        let coordinate = CLLocationCoordinate2D(latitude: ..., longitude: ...)
        annotation.coordinate = coordinate
        mapView.addAnnotation(annotation)
    }
}

请注意,viewDidLoad 不会添加任何注释视图,只会将注释视图 class 注册到您的地图。

产生:


请注意,在旧 iOS 版本中,或者在您有更复杂的注释视图组合的情况下,您可以为您的地图视图设置 delegate,然后实现您自己的 mapView(_:viewFor:),但对于简单的场景通常不需要。