1

我在地图上有 2-10 个注释图钉。当我单击一个按钮时,我希望地图缩小并居中,以便用户可以看到所有图钉。我怎样才能做到这一点?

提前致谢

4

1 回答 1

7

假设您有一个包含所有注释的数组,您可以执行以下操作:

CLLocationCoordinate2D leftTop = CLLocationCoordinate2DMake(-90,180);
CLLocationCoordinate2D rightBottom = CLLocationCoordinate2DMake(90, -180);

for (int i=0; i < [annotations count]; i++) {
    id<MKAnnotation> annotation = (id<MKAnnotation>)[annotation objectAtIndex:i];
    CLLocationCoordinate2D coord = annotation.coordinate;
    if (coord.latitude > leftTop.latitude) {
        leftTop.latitude = coord.latitude;
    }
    if (coord.longitude < leftTop.longitude) {
        leftTop.longitude = coord.longitude;
    }
    if (coord.latitude < rightBottom.latitude) {
        rightBottom.latitude = coord.latitude;
    }
    if (coord.longitude > rightBottom.longitude) {
        rightBottom.longitude = coord.longitude;
    }
}

MKCoordinateSpan regSpan = MKCoordinateSpanMake(leftTop.latitude-rightBottom.latitude, rightBottom.longitude-leftTop.longitude);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(leftTop.latitude-regSpan.latitudeDelta/2, leftTop.longitude+regSpan.longitudeDelta/2);
regSpan.latitudeDelta = MAX(regSpan.latitudeDelta, 0.01);
regSpan.longitudeDelta = MAX(regSpan.longitudeDelta, 0.01);
MKCoordinateRegion reg = MKCoordinateRegionMake(center, regSpan);
if (CLLocationCoordinate2DIsValid(center)) {
    [_mapView setRegion:reg animated:YES];
}
于 2012-05-24T08:18:54.817 回答