2012-02-02 66 views
3

我想在用户点击地图时添加一个mkannotation到我的mkmapview,以便他们可以选择一个位置。在触摸地图上添加mkannotation

我已阅读关于拖动&下降,但如果你想移动到城市的另一个角落,这是有点烦人,因为你必须一步一步地移动引脚。

我怎样才能获得用户点击和移动我的别针的坐标?

谢谢!

回答

9

使用UITapGestureRecognizer得到CGPoint和分接点坐标。

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

然后添加你的目标行动

- (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 
} 
+1

此代码将适用于iOS 3.2或更高版本。 – Alkimake 2012-02-02 15:44:49

+0

工程就像一个魅力!谢谢Alkimake – Ibai 2012-02-02 21:28:43

0

IOS < 3.2,你可以使用这个片段:

- (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]; 
     } 
    } 
} 

是相似的,但不使用UIGestureRecognizer

希望这会有所帮助。