iOS 6 MkMapView在更改区域时保留旋转

时间:2014-01-30 17:40:34

标签: ios mkmapview

在iOS 6中,我试图在不改变旋转的情况下实现更改MkMapView区域的功能。

基本上,我需要能够移动地图以显示区域(因此设置缩放),但我也不想在调用[mapView setRegion:]时旋转地图。

[mapView setCenterCoordinate:]效果很好,但不允许我更改缩放级别。

在iOS 7中,我使用[mapView setCamera:],我有一个中心坐标和指定缩放级别的相机...我在iOS 6中基本上需要此功能。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,最后完全放弃了[mapView setRegion:]方法,转而使用原始区域[mapView setCamera:]并将其作为如何定位相机的基础。

MKCoordinateRegion currentRegion = MKCoordinateRegionMake(center, span);

double altitude = [self determineAltitudeForMapRect:MKMapRectForCoordinateRegion(currentRegion) withHeading:_heading andWithViewport:[[UIScreen mainScreen] bounds].size];

MKMapCamera *currentCamera = [MKMapCamera new];
[currentCamera setHeading:_heading];
[currentCamera setCenterCoordinate:center];
[currentCamera setAltitude:altitude];

[_mapView setCamera:currentCamera];

使用此选项的诀窍是如何确定[currentCamera setAltitude:]值,通常会使用[mapView setRegion:]

自动设置

我的解决方案是改编这个答案https://stackoverflow.com/a/21034410/1130983,它使用一些简单的触发来确定高度,假设地图camara有大约30度的视角。但是,我没有传入多边形,而是直接传入MKMapRect:

- (double)determineAltitudeForMapRect:(MKMapRect)boundingRect withHeading:(double)heading andWithViewport:(CGSize)viewport
{
    // Get a bounding rectangle that encompasses the polygon and represents its
    // true aspect ratio based on the understanding of its heading.
    MKCoordinateRegion boundingRectRegion = MKCoordinateRegionForMapRect(boundingRect);

    // Calculate a new bounding rectangle that is corrected for the aspect ratio
    // of the viewport/camera -- this will be needed to ensure the resulting
    // altitude actually fits the polygon in view for the observer.
    CLLocationCoordinate2D upperLeftCoord = CLLocationCoordinate2DMake(boundingRectRegion.center.latitude + boundingRectRegion.span.latitudeDelta / 2, boundingRectRegion.center.longitude - boundingRectRegion.span.longitudeDelta / 2);
    CLLocationCoordinate2D upperRightCoord = CLLocationCoordinate2DMake(boundingRectRegion.center.latitude + boundingRectRegion.span.latitudeDelta / 2, boundingRectRegion.center.longitude + boundingRectRegion.span.longitudeDelta / 2);
    CLLocationCoordinate2D lowerLeftCoord = CLLocationCoordinate2DMake(boundingRectRegion.center.latitude - boundingRectRegion.span.latitudeDelta / 2, boundingRectRegion.center.longitude - boundingRectRegion.span.longitudeDelta / 2);

    CLLocationDistance hDist = MKMetersBetweenMapPoints(MKMapPointForCoordinate(upperLeftCoord), MKMapPointForCoordinate(upperRightCoord));
    CLLocationDistance vDist = MKMetersBetweenMapPoints(MKMapPointForCoordinate(upperLeftCoord), MKMapPointForCoordinate(lowerLeftCoord));

    double adjacent;

    if (boundingRect.size.height > boundingRect.size.width)
    {
        adjacent = vDist / 2;
    }
    else
    {
        adjacent = hDist / 2;
    }

    double result = adjacent / tan(DEGREES_TO_RADIANS(15));
    return result;
}