I have a MapView that allows me to use a UILongPressGestureRecognizer
to add an annotation, with it's information, to the map. I then added a UITapGestureRecognizer
that I want to remove the annotation when the user clicks on the map. It works great!
The issue I'm having is when I click on the pin, it removes it as well. I wanna be able to click on the pin to the show it's information, but then be able to click on the map view and remove the pin.
class ViewController: UIViewController {
@IBOutlet weak var myMap: MKMapView!
let annotation = MKPointAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
let location = CLLocationCoordinate2D(latitude: 32.92, longitude: -96.46)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
myMap.setRegion(region, animated: true)
var longPress = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
longPress.minimumPressDuration = 2.0
myMap.addGestureRecognizer(longPress)
var tap = UITapGestureRecognizer(target: self, action: "removeAnnotation:")
tap.numberOfTapsRequired = 1
self.myMap.addGestureRecognizer(tap)
}
Remove Annotation Function:
func removeAnnotation(gesture: UIGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended {
self.myMap.removeAnnotation(annotation)
println("Annotation Removed")
}
}
Add Annotation Function:
func addAnnotation(gesture: UIGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Began {
println("Long Press Started")
var touch = gesture.locationInView(self.myMap)
var coordinate = myMap.convertPoint(touch, toCoordinateFromView: self.myMap)
var location = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
var loc = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) -> Void in
if error == nil {
// Placemark data includes information such as the country, state, city, and street address associated with the specified coordinate.
let placemark = CLPlacemark(placemark: placemarks[0] as! CLPlacemark)
var subthoroughfare = placemark.subThoroughfare != nil ? placemark.subThoroughfare : ""
var thoroughfare = placemark.thoroughfare != nil ? placemark.thoroughfare : ""
var city = placemark.subAdministrativeArea != nil ? placemark.subAdministrativeArea : ""
var state = placemark.administrativeArea != nil ? placemark.administrativeArea : ""
var title = "\(subthoroughfare) \(thoroughfare)"
var subTitle = "\(city),\(state)"
//let annotation = MKPointAnnotation()
self.annotation.coordinate = location
self.annotation.title = title
self.annotation.subtitle = subTitle
self.myMap.addAnnotation(self.annotation)
println("Annotation Added")
}
})
}
}
Thank You, Jack