I basically have a map where I add two annotations and they are shown as expected.
Then I´m using the following code:
let annotations = [start, end]
mapView?.showAnnotations(annotations, animated: false)
And this zooms to show my map with the two annotations, but the map could be zoomed in much more and show a more detailed map view.
This is what I get today and this is the expected result that I want.
As you can see the map could be zoomed in a lot more.
Any ideas how to achieve this?
MKCoordinateRegion zoomIn = mapView. region; zoomIn. span. latitudeDelta *= 0.5; [mapView setRegion:zoomIn animated:YES];
Swift 5.0 / 4.2 version of nyxee's answer
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 = MKMapRect.null;
for annotation in annotations {
let annotationPoint = MKMapPoint(annotation.coordinate)
let pointRect = MKMapRect(x: annotationPoint.x, y: annotationPoint.y, width: 0.01, height: 0.01);
zoomRect = zoomRect.union(pointRect);
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 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 = MKMapRect.null
for annotation in annotations {
let aPoint = MKMapPoint(annotation.coordinate)
let rect = MKMapRect(x: aPoint.x, y: aPoint.y, width: 0.1, height: 0.1)
if zoomRect.isNull {
zoomRect = rect
} else {
zoomRect = zoomRect.union(rect)
}
}
if(show) {
addAnnotations(annotations)
}
setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100), animated: true)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With