How to Recognize Which Pin Was Tapped

How to recognize which pin was tapped

In the showDetails: method, you can get the pin tapped from the map view's selectedAnnotations array. Even though the property is an NSArray, just get the first item in the array since the map view only allows one pin to be selected at a time:

//To be safe, may want to check that array has at least one item first.

id ann = [[mapView selectedAnnotations] objectAtIndex:0];

// OR if you have custom annotation class with other properties...
// (in this case may also want to check class of object first)

YourAnnotationClass *ann = [[mapView selectedAnnotations] objectAtIndex:0];

NSLog(@"ann.title = %@", ann.title);



By the way, instead of doing addTarget and implementing a custom method, you can use the map view's calloutAccessoryControlTapped delegate method. The annotation tapped is available in the view parameter:

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view 
calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(@"ann.title = %@", view.annotation.title);
}

Make sure you remove the addTarget from viewForAnnotation if you use calloutAccessoryControlTapped.

Swift: MapKit - Recognize Pin Tap

If you are not receiving a map view delegate message, it is because you have not made yourself the map view's delegate. For example:

self.mapOutlet.delegate = self

How to detect taps on MKMapView but ignore taps on MKAnnotationViews

Finally worked it out for myself. The trick was to use the UIGestureRecognizerDelegate to intercept the tap and decide whether or not the UITapGestureRecognizer should handle it.

The following delegate method code checks what has been tapped on, and ignores it if it's an MKPinAnnotationView:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
{
if (touch.view.self?.isKind(of: MKPinAnnotationView.self) == true)
{
return false
}
return true
}

HowTo detect tap on map annotaition Pin?



You need to implement the following delegate method

 (MKAnnotationView) mapView viewForAnnotation:(id) annotation  

Then just declare following in this method

MKPinAnnotationView *view=[[MKPinAnnotationView alloc]initWithAnnotation:annotation  reuseIdentifier:@"abc"];
view.canShowCallout=YES;
view.calloutOffset=CGPointMake(-20,10); //As per your choice

Then you can add UI to your callout eg UIButton or UIImage as
view.rightCalloutAccesoryView
View.leftCalloutAccesoryView



Related Topics



Leave a reply



Submit