Use this:
extension MKMapView {
/// when we call this function, we have already added the annotations to the map, and just want all of them to be displayed.
func fitAll() {
var zoomRect = MKMapRectNull;
for annotation in annotations {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.01, 0.01);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(100, 100, 100, 100), animated: true)
}
/// we call this function and give it the annotations we want added to the map. we display the annotations if necessary
func fitAll(in annotations: [MKAnnotation], andShow show: Bool) {
var zoomRect:MKMapRect = MKMapRectNull
for annotation in annotations {
let aPoint = MKMapPointForCoordinate(annotation.coordinate)
let rect = MKMapRectMake(aPoint.x, aPoint.y, 0.1, 0.1)
if MKMapRectIsNull(zoomRect) {
zoomRect = rect
} else {
zoomRect = MKMapRectUnion(zoomRect, rect)
}
}
if(show) {
addAnnotations(annotations)
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
}
}
then, after creating an outlet for your MapView, for example as map
, and with you annotations either added to the map of in an array called annotations
, access the above methods like so:
map.fitAll()
OR
map.fitAll(in:annotations, true)
respectively.
Use true or false in the last statement depending on whether you had added the annotations to the map before or not...