Ato*_*iot 15 iphone mkmapview touchesbegan
我试图弄清楚如何根据用户触摸的位置在地图上添加注释.
我已经尝试过对它进行子类化MKMapView并寻找touchesBegan着火,但事实证明,MKMapView它并没有使用标准的触摸方法.
我也尝试过子类化UIView,添加MKMapView一个孩子,然后听HitTest和touchesBegan.这有点工作.如果我有我的地图的全尺寸UIView,那么就有这样的东西
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
return map;
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,我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]);
}
}
Run Code Online (Sandbox Code Playgroud)
但是地图有一些疯狂的行为,就像它不会滚动一样,除非双击,否则它不会放大,但你可以缩小.它只有在我将地图作为视图返回时才有效.如果我没有命中测试方法,地图工作正常,但显然没有得到任何数据.
我是否打算让坐标错误?请告诉我有更好的方法.我知道如何添加注释就好了,我找不到任何在用户触摸地图时添加注释的示例.
小智 43
您可以尝试此代码
- (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];
}
Run Code Online (Sandbox Code Playgroud)
祝一切顺利.
所以我找到了一种方法,最后.如果我创建一个视图并使用相同的帧添加一个地图对象.然后在该视图上监听命中测试,我可以在发送的触摸点上调用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];
}
Run Code Online (Sandbox Code Playgroud)
这是非常粗糙的,当你滚动地图时它仍然不断地调用命中测试,所以你需要处理它,但它开始从触摸地图获取gps坐标.