从iphone上的mkmapview获取一个点的坐标

时间:2010-06-20 17:23:57

标签: iphone mkmapview touchesbegan

我正在试图弄清楚如何根据用户触摸的位置在地图上添加注释。

我尝试对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]);
 }
}

但是地图有一些疯狂的行为,就像它不会滚动一样,除非双击,否则它不会放大,但你可以缩小。它只有在我将地图作为视图返回时才有效。如果我没有命中测试方法,那么地图工作正常,但显然没有得到任何数据。

我是否打算让坐标错误?请告诉我有更好的方法。我知道如何添加注释就好了,我找不到任何在用户触摸地图时添加注释的示例。

5 个答案:

答案 0 :(得分:42)

您可以尝试此代码

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

一切顺利。

答案 1 :(得分: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坐标。

答案 2 :(得分:3)

有点死线程,但由于这是Google的最佳结果,因此可能值得:

您可以使用点击并按住手势识别器来获取坐标并在地图上放置图钉。一切都在freshmob

解释

答案 3 :(得分:1)

Swift 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
}

答案 4 :(得分:0)

迅速4.2

super(TableLiteral, self).__init__()
相关问题