Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Drag and drop the annotation pin in Mkmapview

I have an annotation pin that I use to display the current search location which can be dragged. That annotation pin is dragging and then that pin is showing user drop the pin.How to do like this.

like image 657
vijetha Avatar asked Mar 01 '16 12:03

vijetha


2 Answers

To make an annotation draggable, set the annotation view's draggable property to YES.

This is normally done in the viewForAnnotation delegate method.

For example:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;

    static NSString *reuseId = @"pin";
    MKPinAnnotationView *pav = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (pav == nil)
    {
        pav = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
        pav.draggable = YES;
        pav.canShowCallout = YES;
    }
    else
    {
        pav.annotation = annotation;
    }

    return pav;
}

If you need to handle when the user stops dragging and drops the annotation, see: how to manage drag and drop for MKAnnotationView on IOS?

how to manage drag and drop for MKAnnotationView on IOS?

In addition, your annotation object (the one that implements MKAnnotation) should have a settable coordinate property. You are using the MKPointAnnotation class which does implement setCoordinate so that part's already taken care of.

like image 181
Ashish Thummar Avatar answered Oct 27 '22 15:10

Ashish Thummar


iOS 11.x Swift 4.0 answer, based on Ashish Thummar solution.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "pin"
    var pav: MKPinAnnotationView? = self.mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if pav == nil {
        pav = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pav?.isDraggable = true
        pav?.canShowCallout = true
    } else {
        pav?.annotation = annotation
    }

    return pav
}
like image 22
user3069232 Avatar answered Oct 27 '22 14:10

user3069232