2

我试图弄清楚如何以编程方式重新定位 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 逻辑

[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];
4

1 回答 1

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.coordinate=mMapView.centerCoordinate;
[mMapView selectAnnotation:annotation animated:YES];
于 2012-11-26T15:19:03.013 回答