Create overlay from user interaction on MKMapView?

前端 未结 1 1410
遇见更好的自我
遇见更好的自我 2021-02-04 22:45

I have two questions,

  1. How to create an overlay on a MKMapkitView from user\'s touch down events? i.e. To keep it simple, the user touches down and it creates a

1条回答
  •  无人及你
    2021-02-04 23:15

    Below is an example that creates a circle and drops a pin where the user touches and holds their finger for 1 second. It uses a UILongPressGestureRecognizer which is added to the mapView wherever the map is initialized (eg. viewDidLoad).

    Make sure the mapView's delegate is set also.

    // 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 )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;
    }
    

    0 讨论(0)
提交回复
热议问题