在MKMapView上创建用户交互的叠加层?

时间:2011-03-07 17:48:14

标签: iphone ios ios4 mkmapview

我有两个问题,

  1. 如何根据用户的触地事件在MKMapkitView上创建叠加层?即为了保持简单,用户触摸并创建MKCircle覆盖

  2. 地图应用程序如何在触地时实现“掉针”?有人知道或有一些关于如何完成类似事情的代码示例吗?

  3. 任何指针都将非常感激。正如你所见,我一直在谷歌搜索和阅读大量的文档而没有太大的成功。

1 个答案:

答案 0 :(得分:11)

下面是一个示例,它创建一个圆圈并放下一个用户触摸并保持手指1秒的针脚。它使用UILongPressGestureRecognizer,无论地图初始化的地方都添加到mapView(例如viewDidLoad)。

确保也设置了mapView的委托。

// In viewDidLoad or where map is initialized...
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;  //user must hold for 1 second
[mapView addGestureRecognizer:lpgr];
[lpgr release];

...

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

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

    //add pin where user touched down...
    MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
    pa.coordinate = touchMapCoordinate;
    pa.title = @"Hello";
    [mapView addAnnotation:pa];
    [pa release];

    //add circle with 5km radius where user touched down...
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:touchMapCoordinate radius:5000];
    [mapView addOverlay:circle];
}

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay 
{
    MKCircleView* circleView = [[[MKCircleView alloc] initWithOverlay:overlay] autorelease];
    circleView.fillColor = [UIColor redColor];
    return circleView;
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    static NSString *AnnotationIdentifier = @"Annotation";
    MKPinAnnotationView* pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
    if (!pinView)
    {
        pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
        pinView.pinColor = MKPinAnnotationColorGreen;
        pinView.animatesDrop = YES;
    }
    else
    {
        pinView.annotation = annotation;
    }
    return pinView;
}