I\'m trying to add MKAnnotationView
to MKMapView
but I can\'t do it… Can anyone help me?
Here is my code:
override func vie
You have to show annotation, then you have to add the show annotation method:
let annotation = MKPointAnnotation()
mapVew.showAnnotations([annotation], animated: true)
annotation
is an instance of MKPointAnnotation
.
1- your map view should delegate itself to your view controller 2- you should implement
func mapView(aMapView: MKMapView!, viewForAnnotation annotation: CustomMapPinAnnotation!) -> MKAnnotationView!
this function is called from every annotation added to your Map
3- subclass your annotations to identify them in the viewForAnnotation method
4- in viewForAnnotation, add
if annotation.isKindOfClass(CustomMapPinAnnotation)
{
// change the image here
var pinView = aMapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? YourSubclassedAnnotation
pinView!.image = UIImage(contentsOfFile: "xyz")
}
You need to implement the viewForAnnotation
delegate method and return an MKAnnotationView
from there.
Here's an example:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
//if annotation is not an MKPointAnnotation (eg. MKUserLocation),
//return nil so map draws default view for it (eg. blue dot)...
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"xaxas")
anView.canShowCallout = true
}
else {
//we are re-using a view, update its annotation reference...
anView.annotation = annotation
}
return anView
}
Remember you need to create a plain MKAnnotationView
when you want to use your own custom image. The MKPinAnnotationView
should only be used for the standard pin annotations.
Also note you should not try to access locationManager.location
immediately after calling startUpdatingLocation
. It may not be ready yet.
Use the didUpdateLocations
delegate method.
You also need to call requestAlwaysAuthorization
/requestWhenInUseAuthorization
(see Location Services not working in iOS 8).