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