Convert MKCoordinateRegion to MKMapRect

2019-01-10 11:33发布

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)

9条回答
Deceive 欺骗
2楼-- · 2019-01-10 11:53

Use the built in function MKCoordinateRegionForMapRect

MKCoordinateRegion region = MKCoordinateRegionForMapRect(rect);
查看更多
爷的心禁止访问
3楼-- · 2019-01-10 11:55

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-10 11:57

you can use method to convert MKCoordinateRegion to CGRect

- (CGRect)convertRegion:(MKCoordinateRegion)region toRectToView:(UIView *)view

and use - (MKMapRect)mapRectForRect:(CGRect)rect

or use MKMapPointForCoordinate method to first convert coordinates to MKPoint and use that to form MKMapRect to eventually use setVisibleMapRect:animated:

查看更多
登录 后发表回答