how to manage drag and drop for MKAnnotationView on IOS?
Asked Answered
R

3

12

I'm working without InterfaceBuilder.

I've an instance of MKAnnotationView with setDraggable on YES, In My MKMapView my annotation view is displayed and I can drag and drop it.

How can I execute an method when the drop action is performed? In this method I need the new coordonates of my annotation view.

Rickeyricki answered 22/10, 2010 at 16:12 Comment(0)
A
37

If you've setup your MKAnnotation object with a setCoordinate method properly, then in the didChangeDragState method, the new coordinate should already be in the annotation object:

- (void)mapView:(MKMapView *)mapView 
        annotationView:(MKAnnotationView *)annotationView 
        didChangeDragState:(MKAnnotationViewDragState)newState 
        fromOldState:(MKAnnotationViewDragState)oldState 
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
    }
}

For reference, see the "Marking Your Annotation View as Draggable" section in the docs here. If your app needs to work in an OS earlier than 4.x, the dragging requires more manual work. The link in the docs also points to an example of how to do that if you need to.

Archenteron answered 22/10, 2010 at 17:58 Comment(0)
S
8

you may also want to add the following:

if (newState == MKAnnotationViewDragStateStarting) {
    annotationView.dragState = MKAnnotationViewDragStateDragging;
}
else if (newState == MKAnnotationViewDragStateEnding || newState == MKAnnotationViewDragStateCanceling) {
    annotationView.dragState = MKAnnotationViewDragStateNone;
}

since MKAnnotationView doesn't change its drag state accurately (which could make your map pan with your annotation even after you stop dragging)

Shaikh answered 21/4, 2014 at 16:44 Comment(0)
F
2

Swift solution :

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState)
    {
        if (newState == MKAnnotationViewDragState.ending)
        {
            let droppedAt = view.annotation?.coordinate
            print("dropped at : ", droppedAt?.latitude ?? 0.0, droppedAt?.longitude ?? 0.0);
            view.setDragState(.none, animated: true)    
        }
        if (newState == .canceling )
        {
            view.setDragState(.none, animated: true)           
        }
    }
Fink answered 29/12, 2018 at 5:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.