2017-10-15 6 views
0

J'essaie d'ajouter les broches à la carte en utilisant le tableau de chaînes. mais il n'affiche qu'une seule broche qui n'affiche pas la deuxième broche sur la carte.Comment faire pour déposer des broches sur plusieurs emplacements 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) 
    } 
    }) 
    } 

} 

et ma fonction d'appel

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

Répondre

1

Vous obtenez seulement une goupille de retour parce que vous avez alloué un seul let geocoder = CLGeocoder() donc il suffit de déplacer que dans la boucle for et il fonctionne comme ceci:

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

J'ai ajouté les emplacements var locations tableau qui contiendra toutes vos annotations afin que vous puissiez tous les montrer avec self.myMapView.showAnnotations(locations, animated: true) ... donc emove que si pas nécessaire

+0

Merci. pouvez-vous m'aider à tracer la route entre les broches qui sont dans le tableau. –

+0

Jetez un oeil à quelque chose comme: https://www.hackingwithswift.com/example-code/location/how-to-find-directions-using-mkmapview-and-mkdirectionsrequest – Ladislav