Fitting annotations on a MKMapView while keeping user position centered

后端 未结 1 622
我在风中等你
我在风中等你 2021-01-23 08:09

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

相关标签:
1条回答
  • 2021-01-23 08:33

    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];
    }
    
    0 讨论(0)
提交回复
热议问题