如何在多个位置上删除图钉mapkit swift

时间:2017-10-15 15:47:18

标签: ios swift mapkit mkmapview

我正在尝试使用字符串数组将引脚添加到地图中。但它只显示一个引脚,不会在地图上显示第二个引脚。

func getDirections(enterdLocations:[String])  {
    let geocoder = CLGeocoder()
    // array has the address strings
    for (index, item) in enterdLocations.enumerated() {
    geocoder.geocodeAddressString(item, completionHandler: {(placemarks, error) -> Void in
        if((error) != nil){
            print("Error", error)
        }
        if let placemark = placemarks?.first {

            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

            let dropPin = MKPointAnnotation()
            dropPin.coordinate = coordinates
            dropPin.title = item
            self.myMapView.addAnnotation(dropPin)
            self.myMapView.selectAnnotation( dropPin, animated: true)
   }
    })
    }

}

和我的通话功能

@IBAction func findNewLocation()
{
    var someStrs = [String]()
    someStrs.append("6 silver maple court brampton")
    someStrs.append("shoppers world brampton")
    getDirections(enterdLocations: someStrs)
 }

1 个答案:

答案 0 :(得分:2)

你只收回一个引脚,因为你只分配了一个let geocoder = CLGeocoder()所以只需将它移到for循环中它就会这样工作:

func getDirections(enterdLocations:[String])  {
    // array has the address strings
    var locations = [MKPointAnnotation]()
    for item in enterdLocations {
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(item, completionHandler: {(placemarks, error) -> Void in
            if((error) != nil){
                print("Error", error)
            }
            if let placemark = placemarks?.first {

                let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

                let dropPin = MKPointAnnotation()
                dropPin.coordinate = coordinates
                dropPin.title = item
                self.myMapView.addAnnotation(dropPin)
                self.myMapView.selectAnnotation( dropPin, animated: true)

                locations.append(dropPin)
                //add this if you want to show them all
                self.myMapView.showAnnotations(locations, animated: true)
            }
        })
    }
}

我添加了包含所有注释的位置var locations数组,以便您可以使用self.myMapView.showAnnotations(locations, animated: true)显示所有注释...所以如果不需要则删除