2017-10-15 83 views
0

我正嘗試使用字符串數組將引腳添加到映射。但它只顯示一個引腳不顯示地圖上的第二個引腳。如何在多個位置放置引腳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

你只有一個針回來,因爲你僅配置了一個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)來顯示所有註釋...所以r如果不需要,請留意

+0

謝謝。你能幫我畫出陣列中的引腳之間的路線嗎? –

+0

看看類似這樣的內容:https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest – Ladislav