Here is my code
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)
}
}
}
You are instantiating your MKAnnotationView
, but never using it. But you should not instantiate annotation views yourself, anyway. Let the map view instantiate them for you as needed. All you need to do is define your own annotation view subclass, register it for your map, and you are done:
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")
}
}
And then, in viewDidLoad
, register that annotation view:
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)
}
}
Note, viewDidLoad
isn't adding any annotation views, only registering the annotation view class with your map.
That yields:
Note, in old iOS versions, or in situations where you have more complicated combinations of annotation views, you can set the delegate
for your map view and then implement your own mapView(_:viewFor:)
, but that is generally not needed for simple scenarios.