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

How to Drop pins on multiple locations mapkit swift

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

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)
 }

你只能得到一个引脚,因为你只分配了一个 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)
            }
        })
    }
}

我添加了 locations var locations 数组来保存你所有的注释,这样你就可以用 self.myMapView.showAnnotations(locations, animated: true) 来显示它们...所以如果不需要就删除它