从iPhone上的MKMapView获取一个点的坐标

19

我正在尝试找出如何在用户触摸的位置上放置一个注释标记到地图上。

我曾尝试过子类化 MKMapView 并寻找触摸事件的触发点,但事实证明,MKMapView 不使用标准的touches方法。

我还尝试了子类化 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]);
 }
}

但是这个地图有些奇怪的行为,比如它不能滚动,除非双击缩放,但可以缩小。只有当我将地图返回为视图时才能正常工作。如果没有hit test方法,地图就能正常工作,但显然得不到任何数据。

我获取坐标的方式有误吗?请告诉我是否有更好的方法。我知道如何添加注释,但我找不到任何在用户触摸地图时添加注释的示例。

5个回答

46

你可以尝试这段代码

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

祝一切顺利。


10

我终于找到了一种方法来实现它。如果我创建一个视图并将地图对象添加到其中,然后在该视图上侦听点击测试,我可以在发送的触摸点上调用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];
}

这个代码还比较粗糙,而且当你滚动地图时它仍然会不断调用hit test,所以你需要处理它,但是这是从触摸地图获取GPS坐标的起点。


3

虽然这个帖子有点老,但由于它是谷歌搜索结果的首选,因此可能还是值得一看:

您可以使用“轻触并按住”手势识别器来获取坐标并在地图上放置大头针。所有内容都在freshmob中解释。


3

Swift 4.2

func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

for touch in touches {
    let touchPoint = touch.location(in: mapView)
    let location = mapView.convert(touchPoint, toCoordinateFrom: mapView)
    print ("\(location.latitude), \(location.longitude)")
}}

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接