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

2

27

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?

Footle answered 3/2, 2010 at 17:16 Comment(0)
U
82

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.

Undergrowth answered 26/2, 2010 at 4:45 Comment(3)
Thanks Nate, for fixing the typo.Undergrowth
If you know the annotation you want to programmatically select will be in the map view's visible area you can use [mv annotationsInMapRect:mv.visibleMapRect]. If you're working with large sets of map annotations this will provide a step up in performance.Cr
True. The MapKit API has expanded since this answer was originally provided. The annotationsInMapRect: was added in iOS 4.2.Undergrowth
C
1

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])
Creamy answered 23/5, 2017 at 16:14 Comment(1)
Your code is a strange mix of ObjC (the square brackets) and Swift. Why create an array then discard it?Postgraduate

© 2022 - 2024 — McMap. All rights reserved.