Skip to content

Instantly share code, notes, and snippets.

@tanner0101
Last active January 5, 2024 11:48
Show Gist options
  • Save tanner0101/45741c070508f081657a to your computer and use it in GitHub Desktop.
Save tanner0101/45741c070508f081657a to your computer and use it in GitHub Desktop.
Zoom into and center the MKAnnotations on an MKMapView with one line. With our without animation.
/**
MKMapViewExtensions.swift
Zoom into and center the MKAnnotations on an MKMapView with one line. With our without animation.
<https://gist.github.com/tannernelson/45741c070508f081657a>
*/
import MapKit
extension MKMapView {
func zoomToAnnotations(animated: Bool) {
var zoomRect = MKMapRectNull
for annotation in self.annotations {
if let annotation = annotation as? MKAnnotation {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1)
if MKMapRectIsNull(zoomRect) {
zoomRect = pointRect
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
}
}
let padding = 0.1
let addHeight = zoomRect.size.height * (1 + padding)
let addWidth = zoomRect.size.width * (1 + padding)
zoomRect.size.height += addHeight
zoomRect.size.width += addWidth
zoomRect.origin.x -= addWidth / 2
zoomRect.origin.y -= addHeight / 2
self.setVisibleMapRect(zoomRect, animated: animated)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment