Skip to content

Instantly share code, notes, and snippets.

@vakhidbetrakhmadov
Last active August 5, 2019 11:39
Show Gist options
  • Save vakhidbetrakhmadov/119f6c83e5017b8764a3e41d37241b26 to your computer and use it in GitHub Desktop.
Save vakhidbetrakhmadov/119f6c83e5017b8764a3e41d37241b26 to your computer and use it in GitHub Desktop.
Zooming in on MKMapView to the MIN possible zoom level keeping map 'centered' at a specified coordinate.
import Foundation
import MapKit
extension MKMapView {
/// Region with MIN possible zoom level, such that self.centerCoordinate == center
func region(center: CLLocationCoordinate2D) -> MKCoordinateRegion {
var oldRegion: MKCoordinateRegion?
var newRegion: MKCoordinateRegion?
for latitudeDelta in stride(from: 0.0, through: 180.0, by: 5.0) {
let latitudeDelta = latitudeDelta == 0 ? 1 : latitudeDelta
let span = MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: latitudeDelta * 2)
newRegion = regionThatFits(MKCoordinateRegion(center: center, span: span))
if oldRegion?.span.latitudeDelta.rounded(to: 3) == newRegion?.span.latitudeDelta.rounded(to: 3),
oldRegion?.span.longitudeDelta.rounded(to: 3) == newRegion?.span.longitudeDelta.rounded(to: 3) {
break
}
oldRegion = newRegion
}
return newRegion!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment