2010-06-20 73 views
15

我想知道如何根據用戶觸摸的位置在地圖上添加註釋。從iphone上的mkmapview獲取點座標

我試圖子類的MKMapView,並期待爲touchesBegan火,但事實證明,MKMapView不使用標準觸摸方法。

我也嘗試了分類UIView,添加MKMapView作爲一個孩子,然後聽HitTest和touchesBegan。這有些作用。 如果我有我的地圖UIView的全尺寸,再有這樣的事情

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { 
    return map; 
} 

和這樣的作品,我touchesBegan將能夠使用

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    for (UITouch *touch in touches){ 
    CGPoint pt = [touch locationInView:map]; 
    CLLocationCoordinate2D coord= [map convertPoint:pt toCoordinateFromView:map]; 
    NSLog([NSString stringWithFormat:@"x=%f y=%f - lat=%f long = %f",pt.x,pt.y,coord.latitude,coord.longitude]); 
} 
} 

獲得分數,但隨後的地圖有一些瘋狂的行爲,就像它不會滾動一樣,除非雙擊,否則它不會放大,但可以縮小。並且只有當我將地圖作爲視圖返回時纔有效。如果我沒有命中測試方法,地圖工作正常,但顯然沒有得到任何數據。

我是不是要弄錯座標?請告訴我有更好的方法。我知道如何添加註釋就好,我找不到任何添加註釋的例子,當用戶觸摸地圖的時候和地點。

回答

8

所以我找到了一個辦法,最後。如果我創建一個視圖並使用相同的框架將地圖對象添加到它。然後偵聽該視圖點擊測試,我可以叫convertPoint:toCoordinateFromView:上發送的接觸點,並給它的地圖就像這樣:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ 
    CLLocationCoordinate2D coord= [map convertPoint:point toCoordinateFromView:map]; 
    NSLog(@"lat %f",coord.latitude); 
    NSLog(@"long %f",coord.longitude); 

    ... add annotation ... 

    return [super hitTest:point withEvent:event]; 
} 

這是相當粗糙的是,當你滾動地圖它仍然不斷地調用命中測試,因此您需要處理該測試,但它是從觸摸地圖獲取gps座標的開始。

3

死線程的挖掘一下,但因爲這是頂級的結果在谷歌它可能是值得的:

您可以使用點擊並按住手勢識別,以獲得座標,並在放置圖釘地圖。一切在freshmob

41

,說明你可以試試這個代碼

- (void)viewDidLoad 
{ 
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foundTap:)]; 

    tapRecognizer.numberOfTapsRequired = 1; 

    tapRecognizer.numberOfTouchesRequired = 1; 

    [self.myMapView addGestureRecognizer:tapRecognizer]; 
} 


-(IBAction)foundTap:(UITapGestureRecognizer *)recognizer 
{ 
    CGPoint point = [recognizer locationInView:self.myMapView]; 

    CLLocationCoordinate2D tapPoint = [self.myMapView convertPoint:point toCoordinateFromView:self.view]; 

    MKPointAnnotation *point1 = [[MKPointAnnotation alloc] init]; 

    point1.coordinate = tapPoint; 

    [self.myMapView addAnnotation:point1]; 
} 

所有最優秀的。

+0

斯威夫特版本:http://stackoverflow.com/a/37860496/1151916 – Ramis 2016-06-16 13:19:46

0

雨燕2.2

func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { 
    let point = gestureRecognizer.locationInView(mapView) 
    let tapPoint = mapView.convertPoint(point, toCoordinateFromView: view) 
    coordinateLabel.text = "\(tapPoint.latitude),\(tapPoint.longitude)" 

    return true 
}