Fitting annotations on a MKMapView while keeping user position centered

我的梦境 提交于 2019-12-20 04:54:20

问题


I'm trying to fit all annotations on my MKMapView while keeping the current user position in center of map.

There are already many references[1][2] on how to zoom out a region to fit annotations on the map but they will adjust the current center position e.g. if all annotations are located east of my current user position, it will adjust so the current user position is moved left of the map.

How can I zoom my map out so it will fit all annotations shown but keep the users current position in the center of the map?

Refs:

[1] Zooming MKMapView to fit annotation pins?

[2] - (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);


回答1:


I found this solution to be the most reliable and @Anna suggested it as well so it might be an ok solution.

This is my method (implemented as a method of my inherited MKMapView

- (void)fitAnnotationsKeepingCenter {
  CLLocation *centerLocation = [[CLLocation alloc]
    initWithLatitude:self.centerCoordinate.latitude
    longitude:self.centerCoordinate.longitude];

  // starting distance (do not zoom less than this)
  CLLocationDistance maxDistance = 350;

  for (id <MKAnnotation> vehicleAnnotation in [self annotations]) {
    CLLocation *annotationLocation = [[CLLocation alloc] initWithLatitude:vehicleAnnotation.coordinate.latitude longitude:vehicleAnnotation.coordinate.longitude];
    maxDistance = MAX(maxDistance, [centerLocation distanceFromLocation:annotationLocation]);
  }

  MKCoordinateRegion fittedRegion = MKCoordinateRegionMakeWithDistance(centerLocation.coordinate, maxDistance * 2, maxDistance * 2);
  fittedRegion = [self regionThatFits:fittedRegion];
  fittedRegion.span.latitudeDelta *= 1.2;
  fittedRegion.span.longitudeDelta *= 1.2;

  [self setRegion:fittedRegion animated:YES];
}


来源:https://stackoverflow.com/questions/26416587/fitting-annotations-on-a-mkmapview-while-keeping-user-position-centered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!