I am trying to add the pins to the map using the string array. but it display only one pin does not display second pin on the map.
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)
}
})
}
}
and my calling function
@IBAction func findNewLocation()
{
var someStrs = [String]()
someStrs.append("6 silver maple court brampton")
someStrs.append("shoppers world brampton")
getDirections(enterdLocations: someStrs)
}
You only get one pin back because you allocated just one let geocoder = CLGeocoder()
so just move that into the for
loop and it will work like so:
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)
}
})
}
}
I added the locations var locations
array that will hold all of your annotations so you can show them all with self.myMapView.showAnnotations(locations, animated: true)
...so remove that if not needed