I'm attempting to center an annotation/coordinate within a given MKMapRect. I started by creating the rect which is the visible area between the mapview and another view. This rect is then converted to a rect proportional to the map view in order that it be displayed correctly. I then set the annotation to be displayed in the top left, for testing purposes.
if let annotation = annotation {
let visibleRect = CGRectMake(0, 0, CGRectGetWidth(mapView.frame), CGRectGetMinY(stackViewController.view.frame))
let convertedRect = mapView.convertRect(visibleRect, toView: mapView)
let convertedMapRect = MKMapRectMake(Double(convertedRect.origin.x), Double(convertedRect.origin.y), Double(convertedRect.width), Double(convertedRect.height))
let point = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake((MKMapRectGetMidX(convertedMapRect) - point.x) / 2, (MKMapRectGetMidY(convertedMapRect) - point.y) / 2, convertedMapRect.size.width, convertedMapRect.size.height)
mapView.setVisibleMapRect(pointRect, animated: true)
mapView.selectAnnotation(annotation, animated: true)
}
This code works perfectly, and will display the annotation in the top left as expected. However, when I try to center the annotation within that rect instead of having it in the top left, the map is centered in the sea, rather than in New York. This generally occurs because the point is invalid. Having logged the rect, it returns too small an x and y value when I perform the center calculation. I assume this is because the number of pixels hasn't correctly been converted to the map's coordinate system. Is this why, and how can I scale it?
if let annotation = annotation {
let visibleRect = CGRectMake(0, 0, CGRectGetWidth(mapView.frame), CGRectGetMinY(stackViewController.view.frame))
let convertedRect = mapView.convertRect(visibleRect, toView: mapView)
let convertedMapRect = MKMapRectMake(Double(convertedRect.origin.x), Double(convertedRect.origin.y), Double(convertedRect.width), Double(convertedRect.height))
let point = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake((MKMapRectGetMaxX(convertedMapRect) - point.x) / 2, (MKMapRectGetMaxX(convertedMapRect) - point.y) / 2, convertedMapRect.size.width, convertedMapRect.size.height)
mapView.setVisibleMapRect(pointRect, animated: true)
mapView.selectAnnotation(annotation, animated: true)
}