Search code examples
iosswiftmkmapviewmkannotationview

How to programmatically show MKUserLocation annotation view?


I would like to select the MKUserLocation of the current user location programmatically as soon as the MKMapView shows.

I have tried by doing so:

func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) {
    for annotation in views {
        if annotation.isKindOfClass(MKUserLocation) {
            mapView.selectAnnotation(annotation.annotation!, animated: true)
        }
    }
}

But this doesn't work.

Thanks


Solution

  • The problem is you are checking if MKAnnotationView is of type MKUserLocation. Instead you should check if MKAnnotationView's annotation is MKUserLocation.

    views.forEach() { view in
        if view.annotation is MKUserLocation {
            mapView.selectAnnotation(view.annotation!, animated: true)
        }
    }