更新注释周围的区域

时间:2013-10-13 11:28:23

标签: ios ios7 mkmapview mkannotation

我有一个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];
}

当我运行应用程序时,它没有做任何事情只是向美国展示。 显示注释(在欧洲)。

1 个答案:

答案 0 :(得分:1)

假设首先调用updateRegion(确保needUpdateRegion初始化为YES),updateRegion方法存在两个主要问题:

  1. 如果生成的边界贴图rect的宽度和高度为20,则仅调用setRegion。由于您使用纬度和经度进行计算,这意味着setRegion只会被称为得到的边界图矩形超过20 纬度/经度宽/高。目前尚不清楚这是否符合您的意图。
  2. 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;
    

  3. 请注意,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...
    }