如何使用户位置以地图为中心但允许自由移动?

How can I make the user location centered in a Map but allow free movement?

我有一个 UIViewController 使用 MapKit:

这是我的viewDidLoad

-(void)viewDidLoad {
[super viewDidLoad];

   EventsmapMapView.delegate = self;
   self.locationManager = [[CLLocationManager alloc] init];
   self.locationManager.delegate = self;
   [self.locationManager requestAlwaysAuthorization];
   [self.locationManager startUpdatingLocation];

   EventsmapMapView.showsUserLocation = YES;
   [EventsmapMapView setMapType:MKMapTypeStandard];
   [EventsmapMapView setZoomEnabled:YES];
   [EventsmapMapView setScrollEnabled:YES];

}

这是委托方法 didUpdateUserLocation :

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{

   MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 5000, 5000);
   [self.EventsmapMapView setRegion:[self.EventsmapMapView regionThatFits:region] animated:YES];
}

基本上我的问题是,当加载视图时,我可以在地图中找到自己的位置,但是我无法在地图上四处移动。每次我四处走动时,地图都会自动再次定位我。我知道问题出在 didUpdateUserLocation 但我不确定如何修改代码以防止此行为。很确定这是相对简单的事情。

didUpdateUserLocation: 中,您调用了 setRegion:animated:,这会将可见区域更改为您当前的位置,因为您没有移动。然后你就被锁定了。

您可以考虑以下方法(未测试):

首先,定义一个平移状态标志

BOOL isMapPanning;

初始化一个平移手势识别器,目标指向您的视图

panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[EventsmapMapView addGestureRecognizer:panGesture];

还有一个手势处理程序

-(void)handlePanGesture:(UIPanGestureRecognizer*)sender {
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:
            // Stop map updating...
            isMapPanning = YES;
            break;
        case UIGestureRecognizerStateChanged:
            break;
        case UIGestureRecognizerStateEnded:
            // ... until panning is stop
            isMapPanning = NO;
            break;

        default:
            break;
    }
}

现在,每当 CLLocationManager 调用您的 didUpdateUserLocation 委托时,只需在执行所有操作之前检查平移标志。

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
   if (!isMapPanning) {
       MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 5000, 5000);
       [self.EventsmapMapView setRegion:[self.EventsmapMapView regionThatFits:region] animated:YES];
   }
}

定义 isInitialized 属性.

@property (nonatomic, assign) BOOL isInitialized;

添加保护条款

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{

    if (self.isInitialized) {
        return;
    }

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 5000, 5000);
[self.EventsmapMapView setRegion:[self.EventsmapMapView regionThatFits:region] animated:YES];

    self.isInitialized = YES;

}