Skip to content
Search

CLLocationManager

lastmod 2018-08-17created 2017-01-041 edits

Notes on how to use the CLLocationManager class.

How to get GPS location information

How to initialize a CLLocationManager object.

// CLLocationManagerDelegate를 적용한 클래스의 초기화 메서드 내부.
m_locationManager = [[CLLocationManager alloc] init];
m_locationManager.delegate = self;
[m_locationManager startUpdatingLocation];

How to get GPS longitude/latitude coordinates.

- (void) locationManager: (CLLocationManager*) manager
     didUpdateToLocation: (CLLocation*) newLocation
            fromLocation: (CLLocation*) oldLocation
{
    if (newLocation != nil){
        _x = newLocation.coordinate.longitude;
        _y = newLocation.coordinate.latitude;
    }
}

How to use the Geo-Magnetic Sensor

Getting Heading-Related Events. The steps for receiving heading events are as follows:

  1. Create a CLLocationManager object.
  2. Determine whether heading events are available by calling the headingAvailable class method. (In iOS 3.x and earlier, check the value of the headingAvailable property instead.)
  3. Assign a delegate to the location manager object.
  4. If you want true north values, start location services.
  5. Call the startUpdatingHeading method to begin the delivery of heading events.

Initiating the delivery of heading events.

- (void)startHeadingEvents {
    if (!self.locManager) {
        CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
        // Retain the object in a property.
        self.locManager = theManager;
        locManager.delegate = self;
    }

    // Start location services to get the true heading.
    locManager.distanceFilter = 1000;
    locManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    [locManager startUpdatingLocation];

    // Start heading updates.
    if ([CLLocationManager headingAvailable]) {
        locManager.headingFilter = 5;
        [locManager startUpdatingHeading];
    }
}

When valid data is received through CLLocationManagerDelegate, the locationManager:didUpdateHeading: method is notified. Use headingAccuracy to check validity.

Processing heading events:

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    if (newHeading.headingAccuracy < 0)
        return;

    // Use the true heading if it is valid.
    CLLocationDirection theHeading = ((newHeading.trueHeading > 0) ?
    newHeading.trueHeading : newHeading.magneticHeading);
    self.currentHeading = theHeading;
    [self updateHeadingDisplays];
}

See also

Favorite site