1

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

当我运行该应用程序时,它什么也不做,只显示美国。显示注释(在欧洲)。

4

1 回答 1

1

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

  1. 它仅setRegion在生成的边界图矩形的宽度和高度为 20 时调用。由于您使用纬度和经度度进行计算,因此只有在生成的边界图矩形的纬度/经度宽/高超过 20setRegion时才会调用此方法. 目前尚不清楚这是否是您的意图。
  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;
    


请注意,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...
}
于 2013-10-13T16:32:49.627 回答