Geniouse Geniouse - 25 days ago 18
iOS Question

Swift: How to enable and disable annotations on map view?

I have a code that displays some annotations on a map view. However, i'm trying to have some function where it can be enabled or disabled when a user taps the UISwitch button. Any suggestions on how i can achieve this? Thanks in advance!

let theHouse = MKPointAnnotation()
theHouse.coordinate = CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365)

theHouse.title = "The House, DC"
theHouse.subtitle = "New Jersey, DC"

myMapView.addAnnotation(theHouse)
myAnnotations.append(theHouse.title!)

//Switch that toggles the annotation...
@IBAction func turnOffAnnotations(_ sender: UISwitch) {
//Code that enables and disables the annotation?

if toggle.isOn{
let visible = myMapView.visibleMapRect
let inRect = myMapView.annotations(in: visible)

for annotation: MKAnnotation in myMapView.annotations{
if (inRect.contains(anno as! AnyHashable)){
myMapView.removeAnnotation(annotation)
}
}
} else {
let visible = myMapView.visibleMapRect
let inRect = myMapView.annotations(in: visible)

for annotation: MKAnnotation in myMapView.annotations{
if (inRect.contains(anno as! AnyHashable)){
myMapView.addAnnotation(annotation)
}
}
}
//How to add back the removed annotations here?...
}

Answer

Use viewFor(annotation : MKAnnotation) method :

Swift 3

@IBAction func changeAnnotationsVisibility(_ sender: UISwitch) {
    let annotationVisible = sender.isOn

    for annotation in myMapView.annotations {
        myMapView.view(for: annotation)?.isHidden = !annotationVisible
    }
}