2017-10-15 13 views
0

文字配列を使用してピンをマップに追加しようとしています。表示されているのは1つのピンだけで、マップ上の2番目のピンは表示されません。複数の場所にピンをドロップする方法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) 
} 

答えて

1

あなただけのあなただけの1 let geocoder = CLGeocoder()を割り当てられるので、これだけforループにそれを移動すると、それはそうと同じように動作します1本のピンを取り戻す:

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) ...で表示することができます必要がない場合はそれを避ける

+0

ありがとう。配列にあるピンの間のルートを描くのを助けてくれますか? –

+0

次のようなコードを見てください:https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest – Ladislav

関連する問題