Skip to main content

How to add a push pin to a MKMapView(IOS) when touching?



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.





Thanks a lot



Source: Tips4all

Comments

  1. 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 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.

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

    ReplyDelete
  2. I have a UIImageView with a UILongPressGestureRecognizer attached that never seems to detect a long press gesture no matter how I configure the gesture recognizer.

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.