MKMAPVIEW画面を長押しし、ピンを追加

2948 ワード

地図に関するプログラムを作るとき、私たちはよくユーザーが地図上で位置を指定する必要があります.私たちはピンでマークします.
1、viewDidLoadにキャプチャするジェスチャーを追加する:
UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];

lpress.minimumPressDuration = 0.5;// 0.5   longPress  

lpress.allowableMovement = 10.0;

[m_mapView addGestureRecognizer:lpress];//m_mapView MKMapView   

[lpress release];


2、応答するlongPress方法を実現する:
 
- (void)longPress:(UIGestureRecognizer*)gestureRecognizer{

    if (gestureRecognizer.state == UIGestureRecognizerStateEnded){

        return;

    }

    

    //    

    CGPoint touchPoint = [gestureRecognizer locationInView:m_mapView];

    CLLocationCoordinate2D touchMapCoordinate =

    [m_mapView convertPoint:touchPoint toCoordinateFromView:m_mapView];

    

    MKPointAnnotation* pointAnnotation = nil;

    pointAnnotation = [[MKPointAnnotation alloc] init];

    pointAnnotation.coordinate = touchMapCoordinate;

    pointAnnotation.title = @"  ";

    

    [m_mapView addAnnotation:m_pointAnnotation];

    

    [pointAnnotation release];

}


3,MKMapViewのプロキシメソッドに応答する:
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation{  

    if ([annotation isKindOfClass:[MKUserLocation class]])

    {

        [self.navigationItem.rightBarButtonItem setEnabled:YES];//                

        return nil;

    }



    static NSString* AnnotationIdentifier = @"AnnotationIdentifier";

    MKPinAnnotationView* customPinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];

    

    if (!customPinView) {

        customPinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];

        

        customPinView.pinColor = MKPinAnnotationColorRe;//        

        customPinView.animatesDrop = YES;

        customPinView.canShowCallout = YES;

        customPinView.draggable = YES;//    

        

        //  tips    

        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

        [rightButton addTarget:self action:@selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];

        customPinView.rightCalloutAccessoryView = rightButton;

    }else{

        customPinView.annotation = annotation;

    }

    return customPinView;

}


4、showDetailsを実現する方法:

  
    
- ( void )showDetails:(UIButton * )sender
{

}

MKMapViewの詳細についてはappleの
MapCalloutsの例 .