我有一个mapView
带有一些注释,我想将地图置于annotations
周围。我有以下代码:
- (void)updateRegion {
self.needUpdateRegion = NO;
CGRect boundingRect;
BOOL started = NO;
for (id <MKAnnotation> annotation in self.mapView.annotations){
CGRect annotationRect = CGRectMake(annotation.coordinate.longitude, annotation.coordinate.latitude, 0, 0);
if (!started) {
started = YES;
boundingRect = annotationRect;
} else {
boundingRect = CGRectUnion(boundingRect, annotationRect);
}
} if (started) {
boundingRect = CGRectInset(boundingRect, -0.2, -0.2);
if ((boundingRect.size.width >20) && (boundingRect.size.height >20)) {
MKCoordinateRegion region;
region.center.latitude = boundingRect.origin.x + boundingRect.size.width /2;
region.center.longitude = boundingRect.origin.y + boundingRect.size.height / 2;
region.span.latitudeDelta = boundingRect.size.width;
region.span.longitudeDelta = boundingRect.size.height;
[self.mapView setRegion:region animated:YES];
}
}
}
它在viewDidAppear
执行以产生“滑动效果”:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (self.needUpdateRegion) [self updateRegion];
}
当我运行应用程序时,它没有做任何事情只是向美国展示。 显示注释(在欧洲)。
答案 0 :(得分:1)
假设首先调用updateRegion
(确保needUpdateRegion
初始化为YES
),updateRegion
方法存在两个主要问题:
setRegion
。由于您使用纬度和经度进行计算,这意味着setRegion
只会被称为得到的边界图矩形超过20 度 纬度/经度宽/高。目前尚不清楚这是否符合您的意图。 region
属性正在向后设置。在计算边界图rect时,x
值设置为经度,y
值设置为纬度。但是在设置region.center.latitude
时,它使用的是boundingRect.origin.x
而不是boundingRect.origin.y
。这适用于其他属性,因此代码应该是:
region.center.longitude = boundingRect.origin.x + boundingRect.size.width /2;
region.center.latitude = boundingRect.origin.y + boundingRect.size.height / 2;
region.span.longitudeDelta = boundingRect.size.width;
region.span.latitudeDelta = boundingRect.size.height;
请注意,iOS 7提供了一种新的便捷方法showAnnotations:animated:
来自动显示注释,因此您无需自己计算区域。
所以在updateRegion
中,您可以执行以下操作:
- (void)updateRegion {
self.needUpdateRegion = NO;
//if showAnnotations:animated: is available, use it...
if ([mapView respondsToSelector:@selector(showAnnotations:animated:)])
{
[self.mapView showAnnotations:mapView.annotations animated:YES];
return;
}
//calculate region manually...
}