How do I drop a pin with MapKit?

erotsppa picture erotsppa · Dec 16, 2009 · Viewed 31.4k times · Source

I would like to allow the user of my app to pick a location in the map. The native map has a "drop pin" feature where you can locate something by dropping a pin. How can I do this in MapKit?

Answer

RedBlueThing picture RedBlueThing · Dec 17, 2009

You need to create an object that implements the MKAnnotation protocol and then add that object to the MKMapView:

@interface AnnotationDelegate : NSObject <MKAnnotation> {
    CLLocationCoordinate2D coordinate;
    NSString * title;
    NSString * subtitle;
} 

Instantiate your delegate object and add it to the map:

AnnotationDelegate * annotationDelegate = [[[AnnotationDelegate alloc] initWithCoordinate:coordinate andTitle:title andSubtitle:subt] autorelease];
[self._mapView addAnnotation:annotationDelegate];

The map will access the coordinate property on your AnnotationDelegate to find out where to put the pin on the map.

If you want to customize your annotation view you will need to implement the MKMapViewDelegate viewForAnnotation method on your Map View Controller:

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation

If you would like to implement the pin drag functionality you can read about handling annotation touch events in the Apple OS Reference Library.

You can also check out this article on drag drop with mapkit which refers to a working sample library on GitHub. You can get the coordinates of the dragged annotation by checking the _coordinates member on the DDAnnotation object.