如何在触摸时将推针添加到MKMapView(IOS)?

问题描述:

我必须获得用户触摸MKMapView的点的协调。
我没有使用Interface Builder。
你能给我一个例子或链接。

I had to get the coordonate of a point where the user touch on a MKMapView. I'm not working with the Interface Builder. Can you give me one example or a link.

非常感谢

您可以使用 UILongPressGestureRecognizer 为此。无论您在何处创建或初始化mapview,请先将识别器附加到它:

You can use a UILongPressGestureRecognizer for this. Wherever you create or initialize the mapview, first attach the recognizer to it:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //user needs to press for 2 seconds
[self.mapView addGestureRecognizer:lpgr];
[lpgr release];

然后在手势处理程序中:

Then in the gesture handler:

- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
        return;

    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];   
    CLLocationCoordinate2D touchMapCoordinate = 
        [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];

    YourMKAnnotationClass *annot = [[YourMKAnnotationClass alloc] init];
    annot.coordinate = touchMapCoordinate;
    [self.mapView addAnnotation:annot];
    [annot release];
}

YourMKAnnotationClass是您定义的符合 MKAnnotation 协议。如果您的应用只能在iOS 4.0或更高版本上运行,则可以使用预定义的 MKPointAnnotation

YourMKAnnotationClass is a class you define that conforms to the MKAnnotation protocol. If your app will only be running on iOS 4.0 or later, you can use the pre-defined MKPointAnnotation class instead.

有关创建自己的MKAnnotation类的示例,请参阅示例应用WeatherMap MapCallouts

For examples on creating your own MKAnnotation class, see the sample apps WeatherMap and MapCallouts.