首页 > 解决方案 > 如何使用户位置以地图为中心但允许自由移动?

问题描述

我有一个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但我不确定如何修改代码以防止这种行为。很确定这是相对简单的事情。

标签: objective-cxcodemapkitcore-location

解决方案


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

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

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

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

推荐阅读