Core Location, which is used to locate problems in the system

Source: Internet
Author: User
Tags movable type

Core Location, which is used to locate problems in the system

Core Location is a framework in iOS SDK that provides device locations. You can use three techniques to obtain the location: GPS, cellular, or Wi-Fi. Among these technologies, GPS is the most accurate. If GPS hardware is available, Core Location will give priority to it. If the device does not have a GPS hardware (such as a Wi-Fi iPad) or fails to obtain the current Location using GPS, the Core Location will go back to the next level and choose to use cellular or Wi-Fi.

Most Core Location functions are provided by the Location Manager (CLLocationManager). You can use the Location manager to specify the update frequency and accuracy, and start and stop receiving these updates.

To use Location manager, you must first add the framework Core Location to the project and then import its interface file:

#import <CoreLocation/CoreLocation.h>

And initialize the location manager, specify the update Agent, and some update settings, and then update

CLLocationManager *locManager = [[CLLocationManager alloc] init];locManager.delegate = self;[locManager startUpdatingLocation];

The Location Manager delegate (CLLocationManagerDelegate) has two location-related methods:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation * curLocation = [locations lastObject]; if (curLocation. horizontalAccuracy> 0) {NSLog (@ "current location: %. 0f, %. 0f +/-%. 0f meters ", curLocation. coordinate. longpolling, curLocation. coordinate. latitude, curLocation. horizontalAccuracy);} if (curLocation. verticalAccuracy> 0) {NSLog (@ "Current altitude: %. 0f +/-%. 0f meters ", curLocation. altitude, curLocation. verticalAccuracy );}
}-(Void) locationManager :( CLLocationManager *) manager didFailWithError :( NSError *) error {// this method is called when the location fails. In addition, the update must be stopped at the end because it will be relocated after the failure.
  if(error.code == kCLErrorLocationUnknown)    {        NSLog(@"Currently unable to retrieve location.");    }    else if(error.code == kCLErrorNetwork)    {        NSLog(@"Network used to retrieve location is unavailable.");    }    else if(error.code == kCLErrorDenied)    {        NSLog(@"Permission to retrieve location is denied.");        [manager stopUpdatingLocation];    }
}

 

The first method is successfully located. The manager parameter indicates the location manager instance. locations is an array that is a collection of location changes, which are stored in the order of time changes. To obtain the current location of the device, you only need to access the last element of the array. In the collection, each object type is CLLocation, which includes the following attributes:

Coordinate-coordinates. A struct that encapsulates the longitude and latitude.

Altitude-altitude. Positive numbers represent above sea level, while negative numbers represent below sea level.

HorizontalAccuracy-accuracy (RADIUS) of the position ). The position accuracy is represented by a circle. The actual position may be anywhere in the circle. This circle is jointly determined by coordinate (coordinates) and horizontalAccuracy (RADIUS). The larger the value of horizontalAccuracy, the larger the defined circle, and the lower the positional precision. If the value of horizontalAccuracy is negative, the coordinate value is invalid.

VerticalAccuracy-accuracy of altitude. If it is positive, the error of altitude is the corresponding meter number. If it is negative, the value of altitude (altitude) is invalid.

Speed-speed. This attribute is calculated by comparing the current location and the previous location and comparing the time difference and distance between them. Given the update frequency of the Core Location, the value of the speed attribute is not very accurate unless the movement speed changes little.

 

When the application starts to track user locations, a prompt box Indicating whether to allow positioning is displayed on the screen. If you disable the location service, iOS does not disable the application running, but Location Manager generates an error.

The second method fails to process this positioning. The parameters of this method indicate the cause of the failure. If you disable application locating, the error parameter is kCLErrorDenied. If the Core Location cannot be confirmed after hard work, the error parameter is kCLErrorLocationUnknown. If no source is available for Location retrieval, the error parameter is kCLErrorNetwork.

In general, the Core Location will continue to determine the Location after an error occurs, but it will not do this if the user disallows Location; in this case, use the stopUpdatingLocation method to stop the Location manager.

 

You can specify the location accuracy based on the actual situation. For example, for applications that only need to determine the country in which the user is located, there is no need to require a Core Location accuracy of 10 meters. To specify the precision, you can set the desiredAccuracy of the Location manager before starting the location update. There are 6 enumerated values indicating different precision:

extern const CLLocationAccuracy kCLLocationAccuracyBestForNavigation;extern const CLLocationAccuracy kCLLocationAccuracyBest;extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;extern const CLLocationAccuracy kCLLocationAccuracyKilometer;extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;

After an update is started for the location manager, the update is continuously passed to the location manager for delegation until the update is stopped. You cannot directly control the update frequency, but you can use location manager's distanceFilter attribute for indirect control. Set the property distanceFilter before starting the update, which specifies the number of meters that the device (horizontal or vertical) moves before sending the other update to the delegate. The following code uses the startup Location manager that is suitable for tracking long-distance travelers:

CLLocationManager * locManager = [[CLLocationManager alloc] init]; locManager. delegate = self; locManager. desiredAccuracy = kCLLocationAccuracyHundredMeters; // locManager is located within meters. distanceFilter = 200; // call the agent to update the location [locManager startUpdatingLocation] horizontally or vertically move 200 meters; // update the startup location

P.s. The higher the positioning accuracy, the smaller the value of the distanceFilter attribute, the larger the power consumption of the application.

The Location manager has a headingAvailable attribute that indicates whether the device is equipped with a magnetic compass. If this attribute is YES, you can use the Core Location to obtain the heading information. The received course update is very similar to the received position update. To start receiving course update, you can specify the position manager delegate and set the attribute headingFilter to specify the frequency (measured by the degree of course change) receive updates and call the location manager method startUpdatingHeading:

The Location Manager delegate Protocol defines methods for receiving course updates. The Protocol has two methods related to heading:

- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager{    return YES;}- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{    }

The first method specifies whether the location manager displays a calibration prompt to the user. This prompt will automatically rotate the device 360 °. Since the compass is always self-calibrated, this prompt is only helpful when the compass reading fluctuates sharply. When set to YES, the prompt may distract the user or affect the user's current operation.

The newHeading parameter of the second method is a CLHeading object. CLHeading provides course readings through a set of attributes: magneticHeading and trueHeading. The unit of these values is degree, and the type is CLLocationDirection, that is, double-precision floating point number. This means:

If the heading is 0.0, the forward direction is north;

If the heading is 90.0, the forward direction is east;

If the heading is 180.0, the forward direction is south;

If the heading is 270.0, the forward direction is west.

The CLHeading object also contains the attributes headingAccuracy (precision), timestamp (measurement time of reading), and description (this description is more suitable for writing logs than displaying them to users ). The following shows how to use this method to process course update:

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{    if(newHeading.headingAccuracy >=0)    {        NSString *headingDesc = [NSString stringWithFormat:@"%.0f degrees (true), %.0f degrees (magnetic)",newHeading.trueHeading,newHeading.magneticHeading];                NSLog(@"%@",headingDesc);    }}

 

TrueHeading and magneticHeading indicate the true course and magnetic course respectively. If the location service is disabled, GPS and wifi can only obtain magneticHeading (Magnetic Field heading ). TrueHeading can be obtained only when the location service is enabled ).

The following code demonstrates that when there is a location that determines the longitude and latitude, the distance from the current location and the correct course:

# Import "ViewController. h "# define kdestlong1_113.12 // precision # define kDestLatitude 22.23 // latitude # define kRad2Deg 57.2957795 // 180/π # define kDeg2Rad 0.0174532925 // π/180 @ interface ViewController () @ property (strong, nonatomic) IBOutlet UILabel * lblMessage; @ property (strong, nonatomic) IBOutlet UIImageView * imgView; @ property (strong, nonatomic) CLLocationManager * locationManager; @ property (strong, nona Tomic) CLLocation * recentLocation;-(double) headingToLocation :( CLLocationCoordinate2D) desired current :( partial) current; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; self. locationManager = [[CLLocationManager alloc] init]; self. locationManager. delegate = self; self. locationManager. desiredAccuracy = kCLLocationAccuracyThreeKilometers; self. locationManager. DistanceFilter = 1609; // 1 mile ≈ 1609 meters [self. locationManager startUpdatingLocation]; if ([CLLocationManager headingAvailable]) {self. locationManager. headingFilter = 10; // 10 ° [self. locationManager startUpdatingHeading];}/** According to Movable Type Scripts * http://mathforum.org/library/drmath/view/55417.html ** Javascript: ** var y = Math. sin (dLon) * Math. cos (lat2); * var x = Math. cos (lat1) * Mat H. sin (lat2)-* Math. sin (lat1) * Math. cos (lat2) * Math. cos (dLon); * var brng = Math. atan2 (y, x ). toDeg (); */-(double) headingToLocation :( CLLocationCoordinate2D) desired current :( CLLocationCoordinate2D) current {double lat1 = current. latitude * kDeg2Rad; double lat2 = desired. latitude * kDeg2Rad; double lon1 = current. longpolling; double lon2 = desired. longpolling; double dlon = (lon2-lon1) * kDeg2Rad; double y = si N (dlon) * cos (lat2); double x = cos (lat1) * sin (lat2)-sin (lat1) * cos (lat2) * cos (dlon ); double heading = atan2 (y, x); heading = heading * kRad2Deg; heading = heading + 360.0; heading = fmod (heading, 360.0); return heading ;} // process course-(void) locationManager :( CLLocationManager *) manager didUpdateHeading :( CLHeading *) newHeading {if (self. recentLocation! = Nil & newHeading. headingAccuracy> = 0) {CLLocation * destLocation = [[CLLocation alloc] initWithLatitude: kDestLatitude longpolling: kdestlongdistance]; double course = [self headingToLocation: destLocation. coordinate current: self. recentLocation. coordinate]; double delta = newHeading. trueHeading-course; if (abs (delta) <= 10) {self. imgView. image = [UIImage imageNamed: @ "up_arrow.png"];} else {if (delta> 180) {self. imgView. image = [UIImage imageNamed: @ "right_arrow.png"];} else if (delta> 0) {self. imgView. image = [UIImage imageNamed: @ "left_arrow.png"];} else if (delta>-180) {self. imgView. image = [UIImage imageNamed: @ "right_arrow.png"];} else {self. imgView. image = [UIImage imageNamed: @ "left_arrow.png"] ;}} self. imgView. hidden = NO;} else {self. imgView. hidden = YES ;}// processing and positioning successful-(void) l OcationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations {CLLocation * curLocation = [locations lastObject]; if (curLocation. horizontalAccuracy> = 0) {self. recentLocation = curLocation; CLLocation * destLocation = [[CLLocation alloc] initWithLatitude: kDestLatitude longpolling: kdestlongdistance]; CLLocationDistance distance = [destLocation distanceFromLocation: curLocation]; if (d Istance <500) {[self. locationManager stopUpdatingLocation]; [self. locationManager stopUpdatingHeading]; self. lblMessage. text = @ "you have reached your destination! ";} Else {self. lblMessage. text = [NSString stringWithFormat: @ "% f meters away from the destination", distance] ;}}// processing location failed-(void) locationManager :( CLLocationManager *) manager didFailWithError :( NSError *) error {if (error. code = kCLErrorLocationUnknown) {NSLog (@ "Currently unable to retrieve location. ");} else if (error. code = kCLErrorNetwork) {NSLog (@ "Network used to retrieve location is unavailable. ");} else if (error. code = kCLErrorDenied) {NSLog (@ "Permission to retrieve location is denied. "); [self. locationManager stopUpdatingLocation]; self. locationManager = nil; }}- (void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.