0

I have the following code which maps multiple addresses in my mapView:

@IBOutlet var mapView: MKMapView

var mapThese: Array<AnyObject> = []

override func viewDidLoad() {
    super.viewDidLoad()

    for var index = 0; index < (mapThese.count); ++index {

    var address : String = mapThese[index] as String

    var geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address, {(placemarks: AnyObject[]!, error: NSError!) -> Void in
        if let placemark = placemarks?[0] as? CLPlacemark {
            self.mapView.addAnnotation(MKPlacemark(placemark: placemark))

        }
        })      
    //Here I would like to set the zoom level
}

I need a method to find the bounds of the plotted addresses and then zoom to that level. Your help is greatly appreciated.

Andrea Mugnaini
  • 9,425
  • 3
  • 40
  • 50
agf119105
  • 1,672
  • 4
  • 13
  • 22
  • 1
    Just call mapView.showAnnotations. It will figure out the bounds for you (unless you're really interested in calculating it manually). Also, calling CLGeocoder in a loop like that may result in occasional geocoding failures due to Apple limits. –  Jul 21 '14 at 20:06
  • Hi, Thanks for this @Anna Really appreciate it. Is there an obvious better way to map addresses held in an array? – agf119105 Jul 21 '14 at 20:17
  • @Anna The showAnnotaions method does not seem to support multiple addresses. Is there a way to implement this for multiple addresses? – agf119105 Jul 21 '14 at 20:23
  • showAnnotations doesn't take addresses -- it takes an array of objects that implement MKAnnotation. So in the code shown, call showAnnotations where the comment `//Here I would like...` is like this: `self.mapView.showAnnotations(self.mapView.annotations, animated: true)`. –  Jul 21 '14 at 20:36
  • The problem you'll have is that CLGeocoder is asynchronous and the loop may finish before the geocoding is actually done and showAnnotations may not have anything to show yet. See http://stackoverflow.com/questions/13980930/geocoding-multiple-locations-knowing-when-all-completion-blocks-have-been-ca/13984191#13984191 and http://stackoverflow.com/questions/14195706/multiple-locations-on-map-using-mkmapitem-and-clgeocoder for alternate approaches. –  Jul 21 '14 at 20:42

0 Answers0