How to add pressure contact to MKMapView (IOS) when touching?

I needed to get the coordinate of the point where the user touches MKMapView. I do not work with Interface Builder. Can you give me one example?

+59
ios iphone mkmapview
Oct 18 2018-10-18
source share
2 answers

You can use the UILongPressGestureRecognizer for this . Wherever you create or initialize a map view, first attach a 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 the class you define that conforms to the MKAnnotation protocol. If your application will only run on iOS 4.0 or later, you can use the predefined MKPointAnnotation class.

For examples of creating your own MKAnnotation class, see the MapCallouts sample application.

+194
Oct 18 2018-10-18
source share

Thanks to Anna for such a wonderful answer! Here is the version of Swift, if anyone is interested (the answer has been updated to Swift 4.1 syntax).

Creating a UILongPressGestureRecognizer:

 let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleLongPress(_:))) longPressRecogniser.minimumPressDuration = 1.0 mapView.addGestureRecognizer(longPressRecogniser) 

Gesture Processing:

 @objc func handleLongPress(_ gestureRecognizer : UIGestureRecognizer){ if gestureRecognizer.state != .began { return } let touchPoint = gestureRecognizer.location(in: mapView) let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView) let album = Album(coordinate: touchMapCoordinate, context: sharedContext) mapView.addAnnotation(album) } 
+32
Apr 6 '15 at 6:24
source share



All Articles