Search code examples
swiftmkannotation

Show/Hide annotation when button is pressed


What I want to achieve is when I pressed the button the annotation will show and will hide if I pressed the button again. So far it only show the annotation repeatedly.

Here is my code.

@IBAction func showAnnotation(sender: AnyObject) {
    addAttractionPins()
}

func addAttractionPins() {
    let filePath = NSBundle.mainBundle().pathForResource("Attractions", ofType: "plist")
    let attractions = NSArray(contentsOfFile: filePath!)
    for attraction in attractions! {
        let point = CGPointFromString(attraction["location"] as! String)
        let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y))
        let title = attraction["name"] as! String
        let typeRawValue = (attraction["type"] as! String).toInt()!
        let type = AttractionType(rawValue: typeRawValue)!
        let subtitle = attraction["subtitle"] as! String
        let annotation = AttractionAnnotation(coordinate: coordinate, title: title, subtitle: subtitle, type: type)
        mapView.addAnnotation(annotation)
    }
}

Solution

  • Use this code to add and remove annotation:

    var annotationIsVisible = false
    
    @IBAction func showAnnotation(sender: AnyObject) {
        if !annotationIsVisible {
            addAttractionPins()
            annotationIsVisible = true
    
        }else {
            Map.removeAnnotations(Map.annotations)
            annotationIsVisible = false
        }
    
    }
    
    func addAttractionPins() {
    
        let filePath = NSBundle.mainBundle().pathForResource("Attractions", ofType: "plist")
        let attractions = NSArray(contentsOfFile: filePath!)
        for attraction in attractions! {
            let point = CGPointFromString(attraction["location"] as! String)
            let coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y))
            let title = attraction["name"] as! String
            let typeRawValue = (attraction["type"] as! String).toInt()!
            let type = AttractionType(rawValue: typeRawValue)!
            let subtitle = attraction["subtitle"] as! String
            let annotation = AttractionAnnotation(coordinate: coordinate, title: title, subtitle: subtitle, type: type)
            mapView.addAnnotation(annotation)
        }
    }