获取 MKMapView 中某个点的纬度和经度?
我只是想实现一个小功能,允许系统获取用户触摸的 MKMapView 上的位置。我写了一些代码如下:
#import "UIViewTouch.h"
@implementation UIViewTouch
@synthesize viewTouched;
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *) event{
NSLog(@"Hit Test");
NSLog(@"x = %f, y = %f", point.x, point.y);
MKMapView *mapView = (MKMapView *) [self.subviews objectAtIndex:0];
CLLocationCoordinate2D coordinate = [mapView convertPoint:point toCoordinateFromView:self];
NSLog(@"Lat = %f, Lng = %f", coordinate.latitude,coordinate.longitude);
//MapAnnotation is a custom class and confirms to MKAnnotation.
MapAnnotation *annotation = [[MapAnnotation alloc] initWithCoordinate:coordinate];
[mapView addAnnotation:annotation];
return [super hitTest:point withEvent:event];
}
- (BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event{
return [super pointInside:point withEvent:event];
}
@end
如果我不在 MKMapView
上添加注释,它可以正常工作,否则应用程序将抛出异常:
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'-[TESTViewController openCallout:]: 无法识别的选择器发送到实例 0x6b60180'
有什么想法吗?
多谢!
I just want to implement a small function that allows system to obtain a location on MKMapView
where the user has touched. I wrote some code as following:
#import "UIViewTouch.h"
@implementation UIViewTouch
@synthesize viewTouched;
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *) event{
NSLog(@"Hit Test");
NSLog(@"x = %f, y = %f", point.x, point.y);
MKMapView *mapView = (MKMapView *) [self.subviews objectAtIndex:0];
CLLocationCoordinate2D coordinate = [mapView convertPoint:point toCoordinateFromView:self];
NSLog(@"Lat = %f, Lng = %f", coordinate.latitude,coordinate.longitude);
//MapAnnotation is a custom class and confirms to MKAnnotation.
MapAnnotation *annotation = [[MapAnnotation alloc] initWithCoordinate:coordinate];
[mapView addAnnotation:annotation];
return [super hitTest:point withEvent:event];
}
- (BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event{
return [super pointInside:point withEvent:event];
}
@end
It can work fine if I don't add a annotation on the MKMapView
, otherwise the app will throw a exception:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[TESTViewController
openCallout:]: unrecognized selector sent to instance 0x6b60180'
Any ideas?
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码对我来说看起来不错。异常点处的调用堆栈是什么样的?您是否对明显不存在的选择器
-openCallout:
进行了任何调用?Your code looks fine to me. What does the call stack look like at the exception point? Do you have any calls to the apparently nonexistent selector
-openCallout:
?不完全相关,但您应该在 TouchesBegan:withEvent: 中实现触摸处理。在 hitTest:withEvent: 中自发添加注释充其量是可疑的,因为它可能会向地图视图添加一个视图......
Not entirely related, but you should implement touch-handling in touchesBegan:withEvent:. Spontaneously adding an annotation in hitTest:withEvent: is dubious at best, since it'll probably add a view to the map view...