3

I want to add a mkannotation to my mkmapview when an user taps over the map so they can choose a location.

I've read about the drag&drop but that's a bit annoying if you want to move to the other corner of the city because you have to move step by step the pin.

How can I get the coordinate where a user taps and move my pin there?

Thanks!

Ibai
  • 568
  • 1
  • 7
  • 21

2 Answers2

9

Use UITapGestureRecognizer to get the CGPoint and coordinate of tapped point.

  UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addPin:)];
  [recognizer setNumberOfTapsRequired:1];
  [map addGestureRecognizer:recognizer];
  [recognizer release];

then add your target action

- (void)addPin:(UITapGestureRecognizer*)recognizer
{
  CGPoint tappedPoint = [recognizer locationInView:map];
  NSLog(@"Tapped At : %@",NSStringFromCGPoint(tappedPoint));
  CLLocationCoordinate2D coord= [map convertPoint:tappedPoint toCoordinateFromView:map];
  NSLog(@"lat  %f",coord.latitude);
  NSLog(@"long %f",coord.longitude);

    // add an annotation with coord
}
Alkimake
  • 1,797
  • 14
  • 30
0

On ios < 3.2, you can use this snippet:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{
    if ( touch.tapCount == 1 ) {
      UITouch *touch = [[event allTouches] anyObject];  
      if (CGRectContainsPoint([map frame], [touch locationInView:self.view])) 
      {
         CLLocationCoordinate2D coord= 
                 [map convertPoint:tappedPoint toCoordinateFromView:map];
         NSLog(@"lat  %f",coord.latitude);
         NSLog(@"long %f",coord.longitude);

         // add an annotation with coord

         // or (as example before)
         // [self addPin];
      }
   }
}

it's similar, but don't use UIGestureRecognizer.

Hope this helps.

elp
  • 8,021
  • 7
  • 61
  • 120