缩放到用户位置 iOS 8 MapKit Obj-C

Zooming to users location iOS 8 MapKit Obj-C

我在显示用户当前位置时没有问题,但在尝试缩放到它时遇到问题。我从这里的其他帖子中找到了一些解决方案,但似乎没有任何效果。感谢您的建议,因为我很可能遗漏了一些简单的东西。

这是我目前的情况:

@import CoreLocation;

@interface ViewController () <CLLocationManagerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Get authorization
    CLLocationManager * locationManager = [[CLLocationManager alloc] init];
    // Check before requesting, otherwise it might crash older versions of ios
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    [locationManager requestWhenInUseAuthorization];
}

self.mapView.showsUserLocation = YES;
self.mapView = [[MKMapView alloc] init];
self.mapView.delegate = self;
self.mapView.scrollEnabled = YES;
self.mapView.zoomEnabled = YES;
self.mapView.userTrackingMode = YES;

}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation     *)userLocation
{
//CLLocationCoordinate2D loc = [userLocation coordinate];
//MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
//[self.mapView setRegion:region animated:YES];


//Zoom map to users current location
MKCoordinateRegion region;
MKCoordinateSpan span;

span.latitudeDelta = 0.00001;
span.longitudeDelta = 0.00001;

CLLocationCoordinate2D location = mapView.userLocation.coordinate;

region.span = span;
region.center = location;

[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];

}

@end

我做了这样的事情

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
    {
        if (!self.initialLocation) {
            self.initialLocation = userLocation.location;
            MKCoordinateRegion mapRegion;
            mapRegion.center = mapView.userLocation.coordinate;
            mapRegion.span.latitudeDelta = 0.2;
            mapRegion.span.longitudeDelta = 0.2;

            [mapView setRegion:mapRegion animated: YES];
        }

    }

self.initialLocationCLLocation 的实例。这种方法不断更新用户的当前位置,所以我要做的是检查它是否为零,它应该从一开始就没有,然后 运行 放大代码。第一次之后, self.initialLocation 永远不会为零。

如果你想不断地放大用户的当前位置...去掉 if 语句。

编辑

在 self.initialLocation

的 .h 文件中进行设置

@property (strong, nonatomic) CLLocation *initialLocation;

编辑 2

删除此行

self.mapView = [[MKMapView alloc] init];

无需重新初始化您的 IBOulet