Swift - Add MKAnnotationView To MKMapView

独自空忆成欢 提交于 2019-11-27 03:58:37

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).

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")
}
Abhishek Mishra

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!