2012-02-02 51 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

希望這會有所幫助。