My MKMapView is not fitting correctly the only two annotations I added to it.
There's not much I can think of why this is happening. I have another map in a different view controller and showAnnotations(_:animated) is working correctly. And by comparing their respective code I can't find anything that may cause that behavior.
The code is fundamentally this:
override func viewDidLoad() {
super.viewDidLoad()
annotationOrigin = aCoordinate
annotationDest = bCoordinate
mapView.addAnnotations([annotationOrigin, annotationDest], animated: true)
}
func mapViewDidFinishRenderingMap(_ mapView: MKMapView, fullyRendered: Bool) {
mapView.showAnnotations([annotationOrigin, annotationDest], animated: true)
}
You may try this
func zoomToFitMapAnnotations(aMapView:MKMapView)
{
if(aMapView.annotations.count == 0)
{
return
}
var topLeftCoord = CLLocationCoordinate2D.init(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D.init(latitude: 90, longitude: -180)
for i in 0..<myMapView.annotations.count
{
let annotation = myMapView.annotations[i]
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
let resd = CLLocationCoordinate2D.init(latitude: topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5, longitude: topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)
let span = MKCoordinateSpan.init(latitudeDelta: fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.3, longitudeDelta: fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.3)
var region = MKCoordinateRegion.init(center: resd, span: span);
region = aMapView.regionThatFits(region)
aMapView.setRegion(region, animated: true)
}