Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open call out MKAnnotationView programmatically? (iPhone, MapKit)

I want to open up the callout for an MKPinAnnotationView programmatically. Eg I drop 10 pins on the map, and want to open up the one closest to me. How would I go about doing this?

Apple has specified the 'selected' parameter for MKAnnotationView's, but discourages setting it directly (this doesn't work, tried it).

For the rest MKAnnotationView only has a setHighlighted (same story), and can ShowCallout method..

Any hints if this is possible at all?

like image 352
e75deaf2-fb2a-43e0-91ba-6caad0 Avatar asked Feb 03 '10 17:02

e75deaf2-fb2a-43e0-91ba-6caad0


2 Answers

In your mapViewController create an action method:

- (void)openAnnotation:(id)annotation 
{
    //mv is the mapView
    [mv selectAnnotation:annotation animated:YES];

}

You can then determine the closest annotation based on current location and walking the annotations available in the array.

[mv annotations];

Once the closest annotation is calculated, call:

[self openAnnotation:closestAnnotation];

The mapView should scroll automatically to place your annotation in the center of the display area.

like image 121
Chip Coons Avatar answered Nov 18 '22 06:11

Chip Coons


In swift 3 this is updated to:

func openAnnotation(annotation: MkAnnotation) {
_ = [mapView .selectAnnotation(annotation, animated: true)]
}

and can be called using any annotation (this will open the annotation callout view and attempt to center the annotation on the map)

For example using the second annotation in a hypothetical list of annotations.

openAnnotation(annotation: mapView.annotations[1])
like image 1
S. Doe Avatar answered Nov 18 '22 07:11

S. Doe