从iphone上的mkmapview获取点坐标
问题描述:
我想知道如何根据用户触摸的位置在地图上添加注释。从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]);
}
}
获得分数,但随后的地图有一些疯狂的行为,就像它不会滚动一样,除非双击,否则它不会放大,但可以缩小。并且只有当我将地图作为视图返回时才有效。如果我没有命中测试方法,地图工作正常,但显然没有得到任何数据。
我是不是要弄错坐标?请告诉我有更好的方法。我知道如何添加注释就好,我找不到任何添加注释的例子,当用户触摸地图的时候和地点。
答
所以我找到了一个办法,最后。如果我创建一个视图并使用相同的框架将地图对象添加到它。然后侦听该视图点击测试,我可以叫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坐标的开始。
答
,说明你可以试试这个代码
- (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];
}
所有最优秀的。
答
雨燕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
}
斯威夫特版本:http://stackoverflow.com/a/37860496/1151916 – Ramis 2016-06-16 13:19:46