Search area get coordinates in swift MKMapView

1.8k views Asked by At

How can I get the coordinates of of an area and set it to the focus of the mapview in swift?

I have this code:

var address = "1 Steve Street, Johannesburg, South Africa"
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))
}
})

But that plots a point from an address, how can I get just an area, ie: Johannesburg and set it to be the main area of focus on the map view?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

The placemark has a region property of type CLCircularRegion (a subclass of CLRegion) which gives its center coordinate and radius in meters.

Using that with MKCoordinateRegionMakeWithDistance, you can create an MKCoordinateRegion to set the map view's region.

Example:

var address = "Johannesburg, South Africa"
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
    if let placemark = placemarks?[0] as? CLPlacemark {

        if let pmCircularRegion = placemark.region as? CLCircularRegion {

            let metersAcross = pmCircularRegion.radius * 2

            let region = MKCoordinateRegionMakeWithDistance
                  (pmCircularRegion.center, metersAcross, metersAcross)

            self.mapView.region = region
        }

    }
})