Last active
August 5, 2019 11:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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