在MKMapView上安装注释,同时保持用户位置居中 [英] Fitting annotations on a MKMapView while keeping user position centered

查看:119
本文介绍了在MKMapView上安装注释,同时保持用户位置居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将所有注释放在我的 MKMapView 上,同时将当前用户位置保持在地图中心。

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

关于如何缩小区域以适应地图上的注释已经有很多参考文献[1] [2],但它们会调整当前的中心位置,例如如果所有注释都位于我当前用户位置的东边,它将进行调整,以便当前用户位置向左移动。

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?

参考:

[1] 缩放MKMapView以适合注释引脚?

[2] - (void)showAnnotations:(NSArray *)注释动画:(BOOL)动画NS_AVAILABLE(10_9,7_0);

推荐答案

我发现这个解决方案是最可靠的,而@Anna建议它也是如此可能是一个好的解决方案。

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

这是我的方法(实现为我继承的方法 MKMapView

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];
}

这篇关于在MKMapView上安装注释,同时保持用户位置居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆