MKMapKit.中心地图显示所有MKAnnotation

Bla*_*use 1 iphone objective-c mapkit mkmapview ios

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

提前致谢

Mar*_*ich 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];
}
Run Code Online (Sandbox Code Playgroud)

  • 为了保存你的for循环你可以加倍lat_min = [[annotations valueForKeyPath:@"@ min.latitude"] doubleValue]; double lat_max = [[annotations valueForKeyPath:@"@ max.latitude"] doubleValue]; double lon_min = [[annotations valueForKeyPath:@"@ min.longitude"] doubleValue]; double lon_max = [[annotations valueForKeyPath:@"@ max.longitude"] doubleValue]; (2认同)