如何以编程方式定位mkmapregion以适合注释

时间:2012-11-20 15:26:25

标签: mkmapview

我正在试图弄清楚如何以编程方式重新定位MKMap区域,以便我的注释(在地图加载时自动选择)将全部适合居中。

当前结果:https://www.evernote.com/shard/s46/sh/7c7d2ed8-203c-4878-af8c-83ff77ad7b21/ce7786acdf66b0782fc689b72d1b67e7

所需结果:https://www.evernote.com/shard/s46/sh/21fb0eab-d5c4-4e6d-b05b-322e7dcce8ab/ab816f2a24f11b9c9e15bf55ac648f72

我试图重新定位- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views中的所有内容,但这不起作用。有更好的方法吗?

//这里是viewWillAppear logic

[self.mapView removeAnnotations:self.mapView.annotations];

CLGeocoder *geocoder = [[CLGeocoder alloc] init];

CLGeocodeCompletionHandler completionHandler = ^(NSArray *placemarks, NSError *error) {

if (error) {

  EPBLog(@"error finding placemarks: %@", [error localizedDescription]);

} else {

  if (placemarks) {

    [placemarks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

      CLPlacemark *placemark = (CLPlacemark *)obj;

      if ([placemark.country isEqualToString:@"United States"]) {

        EPBAnnotation *annotation = [EPBAnnotation annotationWithCoordinate:placemark.location.coordinate];

        annotation.title    = self.locationObj.locationName;
        annotation.subtitle = self.locationObj.locationAddress;

        [self.mapView addAnnotation:annotation];

        self.mapView.selectedAnnotations = @[annotation];

        [self.mapView setCenterCoordinate:placemark.location.coordinate];

        /**
         * @todo
         * MOVE THIS OUTTA HERE
         */

        MKCoordinateRegion region = {{0.0f, 0.0f}, {0.0f, 0.0f}};

        region.center = placemark.location.coordinate;

        region.span.longitudeDelta = 0.003f;
        region.span.latitudeDelta  = 0.003f;

        [self.mapView setRegion:region animated:YES];
        [self.mapView regionThatFits:region];

        *stop = YES;
      }
    }];
  }
}
};

[geocoder geocodeAddressString:self.locationObj.locationAddress completionHandler:completionHandler];

1 个答案:

答案 0 :(得分:6)

以下方法将适合地图上的地图以显示所有注释。您可以在Map的didAddAnnotations方法中调用此方法。

- (void)zoomToFitMapAnnotations { 

    if ([mMapView.annotations count] == 0) return;
    int i = 0;
    MKMapPoint points[[mMapView.annotations count]];

    //build array of annotation points
    for (id<MKAnnotation> annotation in [mMapView annotations]){
         points[i++] = MKMapPointForCoordinate(annotation.coordinate);
    }

    MKPolygon *poly = [MKPolygon polygonWithPoints:points count:i];
    [mMapView setRegion:MKCoordinateRegionForMapRect([poly boundingMapRect]) animated:YES]; 
}

你应该看看是否要在可见区域添加用户位置注释。如果不这样做,那么在循环中检查当前注释是否为MkUserLocation并且不在点数组中添加它的点。

if ([annotation isKindOfClass:[MKUserLocation class]]) {
    continue:
}

现在,如果您希望Annotation位于中心并自动选择,请执行此操作

annotation.coordinate=mMapView.centerCoordinate;
[mMapView selectAnnotation:annotation animated:YES];