简体   繁体   中英

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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM