如何清除 swift 中地图视图上的图钉?

How do I clear pins on a mapview in swift?

我的应用程序的一部分包含一个地图视图,它会根据关键字自动搜索。我在我的地图视图中添加了一个文本框和搜索按钮,但我注意到之前的搜索中没有清除图钉。如何在新搜索前清除所有图钉的地图?

import UIKit
import MapKit
import CoreLocation
import iAd

class MapClass: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate, ADBannerViewDelegate {

var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!

var holidayKeyWord = NSString()

@IBOutlet var mapSearchTextbox: UITextField!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet var adBannerView: ADBannerView!
var locationManager: CLLocationManager!

let searchRadius: CLLocationDistance = 2000

override func viewDidLoad() {
    super.viewDidLoad()

    holidayKeyWord = "Restaurant"

    println(holidayKeyWord)
    mapSearchTextbox.text = holidayKeyWord as String

    self.canDisplayBannerAds = true
    self.adBannerView?.delegate = self
    self.adBannerView?.hidden = false

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

}


@IBAction func mapSearchButton(sender: UIButton) {

    //clear pins

    var holidayKeyWord = mapSearchTextbox.text


    if (CLLocationManager.locationServicesEnabled())
    {
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = holidayKeyWord as String
        let search = MKLocalSearch(request: request)
        search.startWithCompletionHandler {
            (response: MKLocalSearchResponse!, error: NSError!) in

            for item in response.mapItems as! [MKMapItem] {
                println(item.name)
                self.addPinToMapView(item.name, latitude: item.placemark.location.coordinate.latitude, longitude: item.placemark.location.coordinate.longitude)

            }
        }
    }



}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    //replace spaces with dashes in wikiDate string

    if (segue.identifier == "amazonToWeb") {
        var wikiDate = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Ddigital-text&field-keywords=\(holidayKeyWord)"
        var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
        DestViewController.wikiDate = wikiDate
    }

    if (segue.identifier == "searchToWeb") {
        var wikiDate = "http://www.bing.com"
        var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
        DestViewController.wikiDate = wikiDate
    }

    if (segue.identifier == "ebayToWeb") {
        var wikiDate = "http://search.ebay.com/\(holidayKeyWord)"
        var DestViewController : WebBrowser = segue.destinationViewController as! WebBrowser
        DestViewController.wikiDate = wikiDate
    }

}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let location = locations.last as! CLLocation
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    self.mapView.setRegion(region, animated: true)
    var latitude: Double = location.coordinate.latitude
    var longitude: Double = location.coordinate.longitude
    let initialLocation = CLLocation(latitude: latitude, longitude: longitude)
    // 1
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = holidayKeyWord as String
    // 2
    let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)

    request.region = MKCoordinateRegion(center: initialLocation.coordinate, span: span)
    // 3
    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler {
        (response: MKLocalSearchResponse!, error: NSError!) in


        for item in response.mapItems as! [MKMapItem] {
            println(item.name)
            //println("Latitude = \(item.placemark.location.coordinate.latitude)")
            //println("Longitude = \(item.placemark.location.coordinate.longitude)")
            self.addPinToMapView(item.name, latitude: item.placemark.location.coordinate.latitude, longitude: item.placemark.location.coordinate.longitude)
        }
    }

    locationManager.stopUpdatingLocation()

    let coordinateRegion = MKCoordinateRegionMakeWithDistance(initialLocation.coordinate, searchRadius * 2.0, searchRadius * 2.0)
    mapView.setRegion(coordinateRegion, animated: true)

}


func addPinToMapView(title: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
    let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let annotation = MyAnnotation(coordinate: location, title: title)

    mapView.addAnnotation(annotation)

}

func removePinFromMapView(title: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
    let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let annotation = MyAnnotation(coordinate: location, title: title)

    mapView.removeAnnotation(annotation)

}


func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("Error: " + error.localizedDescription)
}

您正在通过说 addAnnotation 添加图钉。要删除它们,只需反转:说 removeAnnotation.

遍历您的注释并像这样一一删除它们:

if let annotations = self.mapView.annotations {
    for _annotation in annotations {
        if let annotation = _annotation as? MKAnnotation
        {
            self.mapView.removeAnnotation(annotation)
        }
    }
}

@ezcoding 的答案有一个简短的方法。

mapView.removeAnnotations(mapView.annotations)
[self.mapView removeAnnotations:mapView.annotations];

对于Swift 3.0

func removeAllAnnotations() {
    for annotation in self.mapView.annotations {
        self.mapView.removeAnnotation(annotation)
    }
}