Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PointAnnotation callout on MKMapView appears and then immidiately disappears

I am creating a simple point annotation with a callout inside the UITapGestureRecognizer delegate.

The first time I tap on the map, the pin appears with the callout but the callout immediately disappears after that.

The second time I tap on the same pin, the callout appears and stays there, not sure why it disappears at the first time.

@IBAction func handleMapTouch(recognizer: UITapGestureRecognizer){
    let view = recognizer.view
    let touchPoint=recognizer.locationInView(view)
    var touchCord=CLLocationCoordinate2D()

    touchCord = mapView.convertPoint(touchPoint, toCoordinateFromView:
     mapView)

        mapView.removeAnnotations(mapView.annotations)
        pointAnnotation.coordinate=touchCord
        pointAnnotation.title="ABC"
        pointAnnotation.subtitle="DEF"

        mapView.addAnnotation(pointAnnotation)
        mapView.selectAnnotation(pointAnnotation, animated: true)


}
like image 889
nisgupta Avatar asked Aug 21 '15 10:08

nisgupta


2 Answers

Just in case someone else has the same problem, although Keith's answer works, in my case it disrupts other gestures associated to the map, like pinch and zoom.

For me, delaying some milliseconds the action of showing the callout worked better.

In Swift 3:

let deadlineTime = DispatchTime.now() + .milliseconds(500)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
  mapView.addAnnotation(pointAnnotation)
  mapView.selectAnnotation(pointAnnotation, animated: true)
}
like image 102
joseluissb Avatar answered Oct 31 '22 07:10

joseluissb


I have the same problem. I don't know how to solve it, either, but I found a workaround. Maybe it can help you too.

I used LongPressGesture to replace TapGesture

In Viewdidload:

let longPress = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
longPress.minimumPressDuration = 0.1
self.mapView.addGestureRecognizer(longPress)

In function addAnnotation:

if(gestureRecognizer.state == .Ended){
    self.mapView.removeGestureRecognizer(gestureRecognizer)

    //remove all annotation on the map
    self.mapView.removeAnnotations(self.mapView.annotations)

    //convert point user tapped to coorinate
    let touchPoint: CGPoint! = gestureRecognizer.locationInView(self.mapView)
    let touchMapCoordinate: CLLocationCoordinate2D = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
    showCustomAnnotation(touchMapCoordinate)
}
self.mapView.addGestureRecognizer(gestureRecognizer)
like image 41
Keith Avatar answered Oct 31 '22 08:10

Keith