Sunday 13 September 2015

MKMapview : get radius of map in Swift

Referring : http://jslim.net/blog/2013/07/02/ios-get-the-radius-of-mkmapview/

Here is Swift conversion of getRadius(),

// get center coordinate
let centerCoor = self.mapView.centerCoordinate
let centerLocation = CLLocation(latitude: centerCoor.latitude, longitude: centerCoor.longitude)

// get top left coordinate
let topLeftCoor = self.mapView.convertPoint(CGPointMake(0,0), toCoordinateFromView: self.mapView)
let topLeftLocation =  CLLocation(latitude: topLeftCoor.latitude, longitude: topLeftCoor.longitude)

 // get top right coordinate
 let topRightCoor = self.mapView.convertPoint(CGPointMake(self.mapView.frame.size.width,0), toCoordinateFromView: self.mapView)
 let topRightLocation = CLLocation(latitude: topRightCoor.latitude, longitude: topRightCoor.longitude)

// the distance from center to top left
let hypotenuse:CLLocationDistance = centerLocation.distanceFromLocation(topLeftLocation)

// half of the distance from top left to top right
let x:CLLocationDistance = topLeftLocation.distanceFromLocation(topRightLocation)/2.0

// what we want is this
let y:CLLocationDistance = sqrt(pow(hypotenuse, 2.0) - pow(x, 2.0)) //meter