I'm trying to make an iPhone app which requires users to be able to long press on a place on a map view to drop a pin there. Does anybody know how this is done?
The behaviour is observable in apple maps when you long press on the screen. It will drop a pin and present an annotation saying "dropped pin"
1) Instantiate a UILongPressGestureRecognizer
and add it to the MKMapView
.
2) When the selector gets called after the user has a long press, call the addAnnotation method in MKMapView
with the appropriate title and coordinate.
3) Then make sure you conform to the MKMapViewDelegate
and implement viewForAnnotation:
which will be called right after you add the annotation and return a MKPinAnnotationView
First declare UIGestureRecognizer
in viewDidLoad
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(addWaypoint(longGesture:)))
mapView.addGestureRecognizer(longGesture)
Second add the function for longPress
@objc func addWaypoint(longGesture: UIGestureRecognizer) {
let touchPoint = longGesture.location(in: mapView)
let wayCoords = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let location = CLLocation(latitude: wayCoords.latitude, longitude: wayCoords.longitude)
myWaypoints.append(location)
let wayAnnotation = MKPointAnnotation()
wayAnnotation.coordinate = wayCoords
wayAnnotation.title = "waypoint"
myAnnotations.append(location)
}
I recommend creating the annotations in an array that will serve you later if you want to delete it, like this...
var myAnnotations = [CLLocation]()
If you have different annotations, you can delete only the annotations you want, for that when you add a new annotation add to the array. To delete only one group of annotations just do the following
for dots in myAnnotations{
mapView.removeAnnotation(dots)
}
To delete all annotations try
mapView.removeAnnotations(mapView.annotations)
Apologies for the translation....
Update Swift3
func action(gestureRecognizer:UIGestureRecognizer){
let touchPoint = gestureRecognizer.location(in: mapView)
let newCoordinates = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = newCoordinates
mapView.addAnnotation(annotation)
}