19

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

我尝试MKMapView对 the 进行子类化并寻找touchesBegan触发,但事实证明,MKMapView它不使用标准的触摸方法。

我也尝试过将 a 子类化UIView,将 a 添加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]);
 }
}

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

我是不是要弄错坐标了?请告诉我有更好的方法。我知道如何添加注释就好了,我只是找不到任何在用户触摸地图的位置和时间添加注释的示例。

4

5 回答 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];
}

一切顺利。

于 2013-04-26T06:38:25.287 回答
9

所以我终于找到了一种方法。如果我创建一个视图并使用相同的框架向它添加一个地图对象。然后在该视图上收听命中测试,我可以在发送的接触点上调用 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 坐标的开始。

于 2010-07-14T02:42:03.067 回答
3

有点死线挖掘,但由于这是谷歌的最高结果,它可能是值得的:

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

于 2012-06-02T19:00:56.773 回答
2

斯威夫特 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)")
}}
于 2020-04-16T00:23:06.153 回答
1

斯威夫特 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
}
于 2016-06-16T13:19:22.780 回答