Rotate MapView Based on accelerometer - ios

I am trying to rotate my MapView using CoreMotion around userLocation point. I'm successful in rotating the view but there is one problem: When the mapView is rotated the background white started showing. As shown in this picture (Ignore the red box below):The code I'm using to accomplish this is:
- (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);
}
}];
}
and for the heading
- (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];
}
This method calls the one below:
- (void)outputAccelertionData:(CMAcceleration)acceleration{
//UIInterfaceOrientation orientationNew;
// Get the current device angle
float xx = -acceleration.x;
float yy = acceleration.y;
float angle = atan2(yy, xx);
}
anf finally:
- (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];
}
So, what am I missing here? As far as I gone it has something to do with self.mapView.transform = CGAffineTransformMakeRotation(newRad); but I don't know what to change it to.

Try following code
[self.mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:true];
It works

Related

Stop centralizing the user location when zoom out/in or move to other location in ios

Trying to track user location using MKMapView.
Using below code
-(void)viewDidLoad{
myMapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
arrDate = [[NSMutableArray alloc]init];
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
}
#endif
myMapView.showsUserLocation = YES;
[myMapView setMapType:MKMapTypeStandard];
[myMapView setZoomEnabled:YES];
[myMapView setScrollEnabled:YES];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//[self.locationManager startUpdatingLocation];
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[myMapView setRegion:region animated:YES];
}
-(IBAction)start{
if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.activityType = CLActivityTypeFitness;
// Movement threshold for new events.
self.locationManager.distanceFilter = 8; // meters
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locationss
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(myMapView.userLocation.location.coordinate, 900, 900);
[myMapView setRegion:[myMapView regionThatFits:region] animated:YES];
}
Problem
when i want zoom out/in or moving map to other location while updating the location. it is not working and moving back to present user location.
how can i solve this problem ?
In your #interface add a control flag:
#property (nonatomic, readwrite) BOOL userScrolling;
In your #implementation add/override these bits of code:
- (void)viewDidLoad {
[super viewDidLoad];
// Other set-up code here...
// Used for detecting manual panning/zooming of the map
UIPanGestureRecognizer* panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(didManipulateMap:)];
UIPinchGestureRecognizer* pinchRec = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(didManipulateMap:)];
[panRec setDelegate:self];
[pinchRec setDelegate:self];
[myMapView addGestureRecognizer:panRec];
[myMapView addGestureRecognizer:pinchRec];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (void)didManipulateMap:(UIGestureRecognizer*)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
_userScrolling = YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locationss {
if (!_userScrolling) {
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(myMapView.userLocation.location.coordinate, 900, 900);
[myMapView setRegion:[myMapView regionThatFits:region] animated:YES];
}
}
- (IBAction)locateMeButtonPressed:(id)button {
_userScrolling = NO;
[self.locationManager startUpdatingLocation];
}
That should do it.

Default location in map-kit in ios

I am new to IOS i need to show default location with my latitude and longitude(12.940358, 80.208647).
with annotation pin.
.h file:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface Map_view : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>{
CLLocationManager *locationmgr;
CLGeocoder *geocode;
CLPlacemark *placemark;
}
#property(nonatomic,retain)IBOutlet MKMapView *map11;
.m file:
#synthesize map11;
I don't no where to put my latitude and longitude and how to use please help me.
If you want to show your location with your lat & long with Annotation With Name.
Use this code.
- (void)viewDidLoad {
[super viewDidLoad];
mapVW.showsUserLocation = YES;
CLLocation *loc = [[CLLocation alloc]initWithLatitude:12.940358 longitude:80.208647];
[mapVW setCenterCoordinate:loc.coordinate animated:YES];
CLGeocoder *ceo = [[CLGeocoder alloc]init];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSString *cityName = placemark.locality;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = CLLocationCoordinate2DMake(12.940358, 80.208647);
annotationPoint.title = locatedAt;
MKCoordinateRegion region;
MKCoordinateSpan span1;
span1.latitudeDelta = 0.08;
span1.longitudeDelta = 0.08;
region.span = span1;
region.center = annotationPoint.coordinate;
[mapVW setRegion:region animated:TRUE];
[mapVW regionThatFits:region];
[mapVW addAnnotation:annotationPoint];
[mapVW selectAnnotation:annotationPoint animated:NO];
}
];
}
For centering on user location, you can use the following code:
[mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
For zooming on special locations, you should study how the regions (MKCoordinateRegion) are counted and work, count your latitude and longitude values for the region and display it using call:
[mapView setRegion:myRegion animated:YES];
Try the following code :
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
// 3
[_mapView setRegion:viewRegion animated:YES];
This code will set your region in your map.. Then follow the steps to add annotation in your map..
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate; // Change coordinate as yours
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
Hope it helps..
use this code it will help you:
- (void)location
{
_locationManger =[[CLLocationManager alloc]init];
_locationManger.distanceFilter=kCLDistanceFilterNone;
_locationManger.desiredAccuracy=kCLLocationAccuracyHundredMeters;
[_locationManger startUpdatingLocation];
[map11 setMapType:MKMapTypeStandard];
[map11 setZoomEnabled:YES];
[map11 setScrollEnabled:YES];
MKCoordinateRegion region={ {0.0,0.0 },{0.0,0.0}};
region.center.latitude = 12.940358 ;
region.center.longitude = 80.208647;
region.span.longitudeDelta = 20.20f;
region.span.latitudeDelta = 20.20f;
[map11 setRegion:region animated:YES];
[map11 setDelegate:sender];
}
It will show your desired location as
add this code in your viewdidload
//self.locationManager replace it with your locationmgr
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
in viewdidappear add below code
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake( self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude);
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:userLocation];
[annotation setTitle:#"Your Location"];
[self.mapView addAnnotation:annotation];
//always show the name of annotation
[self.mapView selectAnnotation:annotation animated:YES];
//location 1
CLLocationCoordinate2D loc1Coord = CLLocationCoordinate2DMake(18.998250, 72.848734);//add your latitude and longitude here
MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init];
[annotation1 setCoordinate:loc1Coord];
[annotation1 setTitle:#"title"];
[annotation1 setSubtitle:#"subtitle"];
[self.mapView addAnnotation:annotation1];
}
add this methods
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"loc"];
annotationView.canShowCallout = YES;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return annotationView;
}
Thats it, you can see your latitude and longitude in the map.Let me know if it is working or not?
first You have to set DELEGATE
and Import following in your .h file
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
after that make a property
#property(retain, nonatomic) CLLocationManager *locationManager;
and in ViewDidLoad
mapview.delegate = self;
and then You can do like belew
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
// Add an annotation
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - to get User Current Location.
- (void)getUserLocation{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if([self getDeviceOSVersion].integerValue >= 8) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
}
-(NSString *)getDeviceOSVersion{
return [NSString stringWithFormat:#"%#",[UIDevice currentDevice].systemVersion];
}
#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:#"ERROR" message:#"There was an error retrieving your location"preferredStyle:UIAlertControllerStyleAlert ];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[errorAlert dismissViewControllerAnimated:YES completion:nil];
}];
[errorAlert addAction:ok];
[self presentViewController:errorAlert animated:YES completion:nil];
NSLog(#"Error: %#",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *currentLocation = [locations lastObject];
//currentLocation.coordinate.longitude = currentLocation.coordinate.longitude ;
// latitude = currentLocation.coordinate.latitude;
[self.locationManager stopUpdatingLocation];
}

ioS Google map v2 not working - my location cannot be got

I am working on iOS app using Google Map SDK. I try to set on the CLLocationManager to get location of my device for 10 seconds and right bottom button to get my location instantly. When it comes to the implementation, the app show no response to initiate the method startUpdatingLocation to get my location. Would you please tell me the way to use locationManager to finish the aim?
The following is my working :
-(bool)isNetworkAvailable
{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef address;
address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
CFRelease(address);
bool canReach = success
&& !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
&& (flags & kSCNetworkReachabilityFlagsReachable);
return canReach;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self getTime];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(#"Please enable location services");
return;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
if([self isNetworkAvailable]){
NSLog(#"connected ");
}else {
NSLog(#"not connected ");
}
CarArray = [[NSMutableArray alloc] init];
GMSMarker *marker = [[GMSMarker alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
NSLog(#"assadsd arrived map");
if(latitide!=0.00&&longitude!=0.00) {
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
camera = [GMSCameraPosition cameraWithLatitude:latitide longitude:longitude zoom:12];
}else{
camera = [GMSCameraPosition cameraWithLatitude:22.2855200 longitude:114.1576900 zoom:12];
marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
}
if(desp.length > 0 ){
marker.title = desp;
}
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest ;
self.locationManager.distanceFilter = 5.0f;
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
marker.snippet = #"HK";
marker.map = mapView_;
mapView_.mapType = kGMSTypeSatellite;
mapView_.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
mapView_.myLocationEnabled = YES;
});
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
[mapView_ addObserver:self
forKeyPath:#"myLocation"
options:NSKeyValueObservingOptionNew
context:NULL];
self.view = mapView_;
[self.locationManager startUpdatingLocation];
NSLog(#"assadsd configured d map");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"Please authorize location services");
return;
}
NSLog(#"CLLocationManager error: %#", error.localizedFailureReason);
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"application_name", nil) message:NSLocalizedString(#"location_error", nil) delegate:nil cancelButtonTitle:NSLocalizedString(#"ok", nil) otherButtonTitles:nil];
[errorAlert show];
return;
}
-(void) handleDoubleTap {
NSLog(#"location double tap ");
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
// Optional: check error for desired accuracy
CLLocation* location = [locations lastObject];
NSLog(#"location x : %f" , location.coordinate.longitude);
NSLog(#"location y : %f" , location.coordinate.latitude);
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
[manager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
if (markera == nil) {
markera = [[GMSMarker alloc] init] ;
markera.position = CLLocationCoordinate2DMake( location.coordinate.latitude , location.coordinate.longitude );
markera.groundAnchor = CGPointMake(0.5f, 0.97f); // Taking into account walker's shadow
markera.map = mapView_;
}else {
markera.position = location.coordinate;
}
GMSCameraUpdate *move = [GMSCameraUpdate setTarget:location.coordinate zoom:17];
[mapView_ animateWithCameraUpdate:move];
}

Custom MapView by using Google Maps (iOS)

I have to do Custom MapView, I have done the mkCircle with the radius of 1000 meters with current location.
But I'm not getting how to drag the radius circle.
-(void)viewDidAppear:(BOOL)animated
{
if(![CLLocationManager locationServicesEnabled])
{
NSLog(#"You need to enable location services to use this app");
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Enable Location Services" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
return;
}
if(self.locationManager==nil)
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.pausesLocationUpdatesAutomatically=NO;
NSString *version = [[UIDevice currentDevice] systemVersion];
if([version floatValue] > 7.0f)
{
if ([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
}
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter=50.0f;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
newLocation = locations.lastObject;
coordinate = [newLocation coordinate];
NSLog(#"%f %f",coordinate.latitude,coordinate.longitude);
MKCoordinateRegion r= MKCoordinateRegionMakeWithDistance(coordinate, 400, 400);
self.mapView.region=r;
[self.mapView setCenterCoordinate:coordinate];
Annotation *annot=[[Annotation alloc]initWithTitle:#"My Location" AndCoordinate:coordinate];
[self.mapView addAnnotation:annot];
MKCircle *circle = [MKCircle circleWithCenterCoordinate:coordinate radius:1000];
circle.title = #"";
[self.mapView addOverlay:circle];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKCircle class]])
{
MKCircleRenderer *circleView = [[MKCircleRenderer alloc] initWithCircle:overlay];
circleView.strokeColor=[UIColor blackColor];
circleView.lineWidth=1.2;
circleView.alpha=1;
return circleView;
}
return nil;
}
You can implement Apple Bread crumb class for implementing route drawing.
Please check this link: https://developer.apple.com/library/archive/samplecode/Breadcrumb/Introduction/Intro.html

Make a compass iPhone 3GS

I'm making an compass application, but when my function [localManager startUpdatingHeading], calls it will automatically call the function
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
But the second function is never called, so my program doesn't work. I run this code on my device and nothing happened. Please help me.
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationManager *locaManager = [[CLLocationManager alloc] init];
locaManager.desiredAccuracy = kCLLocationAccuracyBest;
locaManager.delegate = self;
locaManager.headingFilter = .5;
if ([CLLocationManager locationServicesEnabled] && [CLLocationManager
headingAvailable]) {
[locaManager startUpdatingHeading];
[locaManager startUpdatingLocation];
} else {
NSLog(#"Error");
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
if (newHeading.headingAccuracy > 0) {
float magneticHeading = newHeading.magneticHeading;
float trueHeading = newHeading.trueHeading;
label2.text = [NSString stringWithFormat:#"%f", magneticHeading];
label1.text = [NSString stringWithFormat:#"%f", trueHeading];
float heading = -1.0f * M_PI * newHeading.magneticHeading / 180.0f;
imagen.transform = CGAffineTransformMakeRotation(heading);
}
}
Declare this variable in .h file
CLLocationManager *locaManager;
do it in .m file
- (void)viewDidLoad
{
[super viewDidLoad];
locaManager = [[CLLocationManager alloc] init];
locaManager.desiredAccuracy = kCLLocationAccuracyBest;
locaManager.delegate = self;
locaManager.headingFilter = .5;
[locaManager startUpdatingHeading];
[locaManager startUpdatingLocation];
}
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
locationManager.headingFilter = kCLHeadingFilterNone;
[locationManager startUpdatingHeading];
[self.view bringSubviewToFront:_compass_image];
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
// [manager stopUpdatingHeading];
double rotation = newHeading.magneticHeading * 3.14159 / 180;
// CGPoint anchorPoint = CGPointMake(0, -23); // The anchor point for your pin
//[mapView.map setTransform:CGAffineTransformMakeRotation(-rotation)];
[_compass_image setTransform:CGAffineTransformMakeRotation(-rotation)];
// [[mapView.map annotations] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// MKAnnotationView * view = [mapView.map viewForAnnotation:obj];
//
// [view setTransform:CGAffineTransformMakeRotation(rotation)];
// [view setCenterOffset:CGPointApplyAffineTransform(anchorPoint, CGAffineTransformMakeRotation(rotation))];
//
// }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if ([error code] == kCLErrorDenied)
{
// This error indicates that the user has denied the application's request to use location services.
[manager stopUpdatingHeading];
}
else if ([error code] == kCLErrorHeadingFailure)
{
// This error indicates that the heading could not be determined, most likely because of strong magnetic interference.
}
}

Resources