在地图视图的可见rect中显示MKMapViewAnnotations

use*_*435 9 map mapkit mkmapview mkannotation ios

我在Path风格的视差表视图标题中显示MKMapView.要创建效果,mapView边界大于用户可见的区域.我需要设置地图视图区域,以便所有地图的注释都包含在MKMapView的可见矩形中.最好的方法是什么?

MKMapView具有有限的可见区域

为清晰起见编辑:这是一个用例.mapView大小为320 x 380.但是,可见区域由rect(0.0,20.0,320.0,100.0)定义.我需要设置区域,以便所有注释都出现在mapView中的此rect中.

Tam*_*ese 16

设置地图区域以便所有注释都包含在某个部分中,MKMapView可以分三步完成.输入是mapViewannotationsFrame.

  1. 计算MKMapRect mapRect包含所有注释的内容.
  2. mapView.bounds和计算填充插入annotationsFrame.
  3. 调用-setVisibleMapRect:edgePadding:animated:地图视图.

下面是测试的屏幕截图.红色叠加显示了annotationsFrame.

screen一个测试的镜头,显示所有注释都在给定的注释框架内

这是代码.注意:这是一种简化将其添加到代码中的方法,并且没有针对边缘情况进行测试,例如传入具有相同坐标的n个注释,或者注释距离太远以至于地图也必须缩小很多,或坐标跨越地图边缘+/- 180度经度.

- (void)zoomAnnotationsOnMapView:(MKMapView *)mapView toFrame:(CGRect)annotationsFrame animated:(BOOL)animated
{
    if (_mapView.annotations.count < 2) return;


    // Step 1: make an MKMapRect that contains all the annotations

    NSArray *annotations = _mapView.annotations;

    id <MKAnnotation> firstAnnotation = [annotations objectAtIndex:0];
    MKMapPoint minPoint = MKMapPointForCoordinate(firstAnnotation.coordinate);
    MKMapPoint maxPoint = minPoint;

    for (id <MKAnnotation> annotation in annotations) {
        MKMapPoint point = MKMapPointForCoordinate(annotation.coordinate);
        if (point.x < minPoint.x) minPoint.x = point.x;
        if (point.y < minPoint.y) minPoint.y = point.y;
        if (point.x > maxPoint.x) maxPoint.x = point.x;
        if (point.y > maxPoint.y) maxPoint.y = point.y;
    }

    MKMapRect mapRect = MKMapRectMake(minPoint.x, minPoint.y, maxPoint.x - minPoint.x, maxPoint.y - minPoint.y);


    // Step 2: Calculate the edge padding

    UIEdgeInsets edgePadding = UIEdgeInsetsMake(
        CGRectGetMinY(annotationsFrame),
        CGRectGetMinX(annotationsFrame),
        CGRectGetMaxY(mapBounds) - CGRectGetMaxY(annotationsFrame),
        CGRectGetMaxX(mapBounds) - CGRectGetMaxX(annotationsFrame)
    );


    // Step 3: Set the map rect

    [mapView setVisibleMapRect:mapRect edgePadding:edgePadding animated:animated];
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个完美的位置(谁没有),这里有三件事需要考虑:

  1. 代码确保所有坐标都在annotationsFrame,但注释本身可能在外面.为了防止这种情况,只需使用更多填充.例如,如果您的注释是20x20并且以坐标为中心,则在所有边上再使用10个填充.
  2. 在iOS 7下方,地图没有缩放到完美的缩放比例,而是缩放到下一个图块尺寸(2的幂).因此,注释周围将有比所需更多的空间,如屏幕截图所示.
  3. 在iOS 7上,地图视图不仅可以完美缩放,还可以自动关注状态栏.要使计算正确,您需要从iOS 7上的顶部填充中减去状态栏高度.


And*_*ree 5

从 iOS 7.0 开始,这可以通过showAnnotations.

迅速:

mapView.showAnnotations(mapView.annotations, animated: true)
Run Code Online (Sandbox Code Playgroud)

目标-C:

[mapView showAnnotations:mapView.annotations animated:YES];
Run Code Online (Sandbox Code Playgroud)

上面的语句将调整地图视图的可见矩形以显示所有注释。