2016-07-18 2 views
1

Я пытаюсь повернуть мой MapView используя CoreMotion вокруг userLocation пункт. Мне удастся повернуть вид, но есть одна проблема: Когда поворот mapView запустит фоновый белый цвет. Как показано на рисунке (Не обращайте внимания на красный квадрат ниже): enter image description here
код я использую для достижения этой цели является:Повернуть 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);, но я не знаю, как его изменить.

+1

если вы хотите следовать с заголовком вы можете использовать self.mapView.setUserTrackingMode (MKUserTrackingMode.FollowWithHeading, анимированные: правда). – sanman

+0

@sanman да именно это то, что мне нужно ... эта линия работает отлично, но если попытаться двигаться очень быстро, она разбила приложение, говорящее «EXE_BAD_ACCESS», какие-нибудь идеи, как с этим справиться? Я сделал это '[UIView animateWithDuration: 0.6 delay: 0 options: UIViewAnimationOptionCurveEaseInOut анимации:^{ //self.mapView.transform = CGAffineTransformMakeRotation (newRad); [self.mapView setUserTrackingMode: MKUserTrackingModeFollowWithHeading animated: true]; } завершение: nil]; ' –

+0

@sanman Я прокомментировал' [self.mapView setCenterCoordinate: userLocation.location.coordinate animated: YES]; 'in' didUpdateUserLocation', и он больше не сбой. :) Большое вам спасибо за вашу помощь. –

ответ

1

Try следующий код

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

Он работает

+0

он продолжает сбой приложения без каких-либо ошибок в описании, но иногда он показывает '__NSCFNumber isPitched', а иногда' EXE_BAD_ACCESS' –

+1

Я не знаю причину сбоя, но надеюсь, что это поможет http://stackoverflow.com/questions/16617563/crash-on-setusertrackingmode-with-mkmapview-when-zoomed-in :) – sanman

Смежные вопросы