I have a square MKMapView in my app, and I wish to set a center point and the exact height/width of the view in meters.
Creating an MKCoordinateRegion and setting the map to it (as in this code...
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(center_coord, 1000.0, 1000.0);
[self.mapView setRegion:region animated:YES];
..) doesn't work properly because using regions here just means that at least that region is displayed, typically more than the region is.
I'm planning on using setVisibleMapRect:animated: method instead, as I believe this will zoom to the actual MKMapRect passed.
So, is there a simple way to convert between an MKcoordinateRegion and an MKMapRect? Perhaps getting the top-left and bottom-right coordinates of the region, and using them to the make the MKMapRect?
I couldn't see anything handy in the Map Kit Functions Reference.
(Using iOS 5, Xcode 4.2)
@David's answer, in Swift 3
@Bogdan
I think it should be:
According to apple api reference, MKCoordinateRegion.center represents the center point of the region; and MKCoordinateSpan.latitudeDelta represents the amount of north-to-south distance (measured in degrees) to display on the map; MKCoordinateSpan.longitudeDelta represents amount of east-to-west distance (measured in degrees) to display for the map region.
Use MKMapPointForCoordinate to convert the 2 point of the region (top/left and bottom/right), then create the MKMapRect using the 2 MKMapPoints
The answer @David gave (and consequently the Swift 3 version by @onmyway133) has a significant error whenever the region crosses over the anti-meridian from the Eastern Hemisphere (longitude 0 degrees to 180 degrees) to the Western Hemisphere (longitude -180 degrees to 0 degrees). The width of the MKMapRect will be bigger than it should be (usually much bigger).
Here is the fix (for the Swift 3 code):
Taking an MKCoordinateRegion, converting it into an MKMapRect with the code above, and then turning it back into an MKCoordinateRegion using MKCoordinateRegionForMapRect() gives me very good agreement between the input region and the output region everywhere on the map.
Still have to be a bit more careful about crossing the meridian (as well as wrapping around the poles) otherwise MKMapPointForCoordinate returns -1, -1:
Some test case code (using Nimble):
This is a Swift verion to Leo & Barnhart solution