ios - 在保持用户位置居中的同时在 MKMapView 上安装注释

标签 ios iphone mkmapview mkuserlocation

我试图在我的 MKMapView 上添加所有注释,同时将当前用户位置保持在 map 中心。

关于如何缩小区域以适应 map 上的注释,已经有很多引用资料[1][2],但它们会调整当前的中心位置,例如如果所有注释都位于我当前用户位置的东边,它将进行调整,以便将当前用户位置移到 map 的左侧。

我如何缩小我的 map 以适应显示的所有注释,同时保持用户当前位置在 map 中心?

引用:

[1] Zooming MKMapView to fit annotation pins?

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

最佳答案

我发现这个解决方案是最可靠的,@Anna 也推荐了它,所以它可能是一个不错的解决方案。

这是我的方法(实现为我继承的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];
}

关于ios - 在保持用户位置居中的同时在 MKMapView 上安装注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26416587/

相关文章:

iOS 在应用程序中打开附件。没有这样的文件或目录

iphone - 如何使 UITableView 中的单元格可移动但不可删除?

iphone - 2 字节数组/内联 c 数组的相等性

iPhone:如何使用界面生成器绘制简单的彩色矩形?

swift - 无法从 GEOSwift 库解析几何 LineString 以在 MapView 中显示折线

iphone - 重绘MKAnnotationView

ios - 从 iTunes 复制文件并从应用程序访问

ios - 查找对 System.IO.FileSystem.Watcher.dll 的引用

iphone - 如何格式化 root.plist 中的字符串?

iphone - 使 MKMapView 透明但保持覆盖层不透明