Convert MKCoordinateRegion to MKMapRect

Jon Cox picture Jon Cox · Feb 14, 2012 · Viewed 33.1k times · Source

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)

Answer

leo picture leo · Mar 28, 2013

To add another implementation to the pile:

- (MKMapRect)MKMapRectForCoordinateRegion:(MKCoordinateRegion)region
{
    MKMapPoint a = MKMapPointForCoordinate(CLLocationCoordinate2DMake(
        region.center.latitude + region.span.latitudeDelta / 2, 
        region.center.longitude - region.span.longitudeDelta / 2));
    MKMapPoint b = MKMapPointForCoordinate(CLLocationCoordinate2DMake(
        region.center.latitude - region.span.latitudeDelta / 2, 
        region.center.longitude + region.span.longitudeDelta / 2));
    return MKMapRectMake(MIN(a.x,b.x), MIN(a.y,b.y), ABS(a.x-b.x), ABS(a.y-b.y));
}

NB: There are many ways to convert between MKMapRect and MKCoordinateRegion. This one certainly is not the exact inverse of MKCoordinateRegionMakeWithDistance(), but approximates it fairly well. So, be careful converting back and forth, because information can be lost.