我在路径样式视差表视图标题内显示 MKMapView。为了创建效果,mapView 边界大于用户可见的区域。我需要设置地图视图区域,以便所有地图注释都包含在 MKMapView 的可见矩形内。最好的方法是什么?
为了清楚起见编辑:这是一个用例。 mapView 大小为 320 x 380。然而,可见区域由矩形 (0.0, 20.0, 320.0, 100.0) 定义。我需要设置区域,以便所有注释都出现在地图视图中的该矩形中。
设置地图区域,使所有注释都包含在地图的特定部分中MKMapView
可以分三步完成。输入是mapView
和annotationsFrame
.
- 计算一个
MKMapRect
mapRect
包含所有注释。
- 计算填充插入量
mapView.bounds
and annotationsFrame
.
- Call
-setVisibleMapRect:edgePadding:animated:
在地图视图上。
下面是测试的屏幕截图。红色覆盖层显示annotationsFrame
.
这是代码。Beware:这一切都在一种方法中,可以简化将其添加到代码中的过程,并且未针对边缘情况进行测试例如传入具有相同坐标的 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];
}
如果您追求完美的展示位置(谁不追求完美的展示位置),则需要考虑以下三件事:
- 该代码确保所有坐标都在
annotationsFrame
,但注释本身可能位于外部。为了防止这种情况,只需使用更多的填充即可。例如,如果您的注释为 20x20 且以坐标为中心,则在所有边上再使用 10 个填充。
- 在 iOS 7 以下,地图不会缩放到完美的缩放比例,而是缩放到下一个图块大小(2 的幂)。因此,注释周围会有比所需更多的空间,如屏幕截图所示。
- 在 iOS 7 上,地图视图不仅会完美缩放,还会自动关注状态栏。为了使计算正确,您需要从 iOS 7 的顶部填充中减去状态栏高度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)