Повернуть MapView на основе акселерометра

Я пытаюсь повернуть свой MapView, используя CoreMotion вокруг точки userLocation. Мне удалось повернуть вид, но есть одна проблема: При повороте mapView фон стал отображаться белым. Как показано на этом рисунке (не обращайте внимания на красное поле ниже):введите описание изображения  здесь
Для этого я использую следующий код:

- (void)viewDidLoad {
locationManager = [[CLLocationManager alloc] init];
    _mapView.delegate = self;
    locationManager.delegate = self;
[locationManager requestWhenInUseAuthorization];

    [locationManager startUpdatingLocation];

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

 locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.headingFilter = 1;
    [locationManager startUpdatingHeading];

    motionManager = [[CMMotionManager alloc] init];
    motionManager.accelerometerUpdateInterval = 0.01;
    motionManager.gyroUpdateInterval = 0.01;

    [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
                                        withHandler:^(CMAccelerometerData  *accelerometerData, NSError *error) {
                                            if (!error) {
                                                [self outputAccelertionData:accelerometerData.acceleration];
                                            }
                                            else{
                                                NSLog(@"%@", error);
                                            }
                                        }];

}

и для заголовка

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {

    //self.lblGrados.text = [NSString stringWithFormat:@"%.0f°", newHeading.magneticHeading];

    // Convert Degree to Radian and move the needle
    float newRad =  -newHeading.trueHeading * M_PI / 180.0f;

    [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.mapView.transform = CGAffineTransformMakeRotation(newRad);
    } completion:nil];
}

Этот метод вызывает следующий:

- (void)outputAccelertionData:(CMAcceleration)acceleration{
    //UIInterfaceOrientation orientationNew;

    // Get the current device angle
    float xx = -acceleration.x;
    float yy = acceleration.y;
    float angle = atan2(yy, xx);
}

и наконец:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800.0f, 200.0f);
    //[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

    [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    [self.mapView setRegion:region animated:YES];
}
- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}
- (NSString *)deviceLat {
    return [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude];
}
- (NSString *)deviceLon {
    return [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude];
}
- (NSString *)deviceAlt {
    return [NSString stringWithFormat:@"%f", locationManager.location.altitude];
}

Итак, что мне здесь не хватает? Насколько я понял, это как-то связано с self.mapView.transform = CGAffineTransformMakeRotation(newRad);, но я не знаю, на что его поменять.


person Chaudhry Talha    schedule 18.07.2016    source источник
comment
если вы хотите следить за заголовком, вы можете использовать self.mapView.setUserTrackingMode(MKUserTrackingMode.FollowWithHeading, анимированный: true) .   -  person Sanman    schedule 18.07.2016
comment
@sanman да, это именно то, что мне нужно ... эта линия работает отлично, но если попытаться двигаться очень быстро, приложение вылетит, говоря: EXE_BAD_ACCESS есть идеи, как с этим справиться? Я сделал это [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ //self.mapView.transform = CGAffineTransformMakeRotation(newRad); [self.mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:true]; } completion:nil];   -  person Chaudhry Talha    schedule 18.07.2016
comment
@sanman Я прокомментировал [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES]; в didUpdateUserLocation, и он больше не падает. :) Спасибо большое за вашу помощь.   -  person Chaudhry Talha    schedule 18.07.2016
comment
Вы можете добавить строку в viewDidLoad вместо этого блока. Я не уверен, почему он падает.   -  person Sanman    schedule 18.07.2016
comment
Рад, что у вас получилось :)   -  person Sanman    schedule 18.07.2016
comment
@sanman Я использую его в методе делегата - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation. Поскольку у меня нет userLocation на viewDidLoad   -  person Chaudhry Talha    schedule 18.07.2016
comment
Он по-прежнему перенаправляется после получения местоположения, поэтому я предложил это.   -  person Sanman    schedule 18.07.2016


Ответы (1)


Попробуйте следующий код

[self.mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:true];

Оно работает

person Sanman    schedule 18.07.2016
comment
приложение продолжает крашиться без каких-либо ошибок, показанных в описании, но иногда показывает __NSCFNumber isPitched, а иногда EXE_BAD_ACCESS - person Chaudhry Talha; 18.07.2016
comment
Я не знаю причину сбоя, но надеюсь, что это поможет stackoverflow.com/questions/16617563/ :) - person Sanman; 18.07.2016