IOS Study Notes 19-map (1) Positioning CoreLocation

Source: Internet
Author: User

IOS Study Notes 19-map (1) Positioning CoreLocation
I. Positioning Introduction

Currently, many social networking, e-commerce, and Group Buying applications have introduced map and positioning functions. It seems that map functions are no longer unique to map applications and navigation applications. Indeed, with the map and positioning functions, our life is indeed more colorful, greatly changing our way of life. You must be familiar with the map and navigation functions first.Positioning.

In iOS CoreLocationFramework.

CoreLocationIt can be used independently and with the map development framework.MapKitIt is completely independent, but often map development should be used with the positioning framework.

CoreLocationFunctions: location and Inverse

Ii. Positioning core categories

Positioning is a very common function. For example, if you allow the software to locate a map software after it is opened, the software is automatically locked to the current position after it is opened, if the user's mobile phone moves, the current location will also change. To implement this function, you need to useCoreLoactionMediumCLLocationManagerClass. The following describes how to use this class:

1. Class methods:
+ (BOOL) locationServicesEnabled;/* return whether the user enables the positioning service */+ (clthorizationstatus) authorizationStatus;/* locate the service authorization status, return the enumeration type */typedefNS_ENUM (int, clthorizationstatus) {kclothorizationstatusnotdetermined = 0,/* the user has not decided whether to enable the positioning service */kclothorizationstatusrestricted,/* No user authorization */kclothorizationstatusdenied, /* the user is prohibited from using the locating or locating service in the closed state */kclthorizationstatusauthorizedalways,/* foreground and background positioning authorization */kclthorizationstatusauthorizedwheninuse,/* foreground positioning authorization */};
2. Object Property: Positioning Accuracy desiredAccuracy:
Enumeration type:
Minimum distance from Location Information Update distanceFilter:
Floating Point number. The default value is kCLDistanceFilterNone3. Object method:
# Pragma mark-positioning tracking-(void) startUpdatingLocation;/* start locating tracking */-(void) stopUpdatingLocation; /* Stop positioning tracking */# pragma mark-navigation tracking-(void) startUpdatingHeading;/* Start navigation direction tracking */-(void) stopUpdatingHeading; /* stop navigation direction tracking */# pragma mark-region Positioning tracking-(void) startMonitoringForRegion :( CLRegion *) region; /* start locating and tracking a region */-(void) stopMonitoringForRegion :( CLRegion *) region; /* Stop locating and tracking a region */# pragma mark-authorization request-(void) requestWhenInUseAuthorization;/* request to obtain the application's foreground location authorization */-(void) requestAlwaysAuthorization; /* request to obtain the application's frontend and backend positioning authorization */
4. Common proxy Methods CLLocationManagerDelegate:
/* Call after the location is changed. The first location will also call */-(void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray *) locations; /* call */-(void) locationManager (CLLocationManager *) manager didUpdateHeading :( CLHeading *) newHeading after the navigation direction changes;/* call */-(void) after entering a certain area) locationManager :( CLLocationManager *) manager didEnterRegion :( CLRegion *) region;/* call */-(void) locationManager (CLLocationManager *) manager didExitRegion :( CLRegion *) region; /* call */-(void) locationManager (CLLocationManager *) manager didChangeAuthorizationStatus (clthorizationstatus) when the user's authorization status changes;
3. For simple positioning, first import the CoreLocation framework in the project, and then import the header file:
#import 
  
There are also some differences in iOS versions, mainly divided into: positioning before iOS8.0 using positioning after iOS8.0 using positioning before iOS8.0 using: 1.1 foreground positioning:
-(Void) viewDidLoad {[super viewDidLoad]; if (! [CLLocationManager locationServicesEnabled]) {NSLog (@ "the locating service may not be opened yet. Please set it to open! "); Return;} [self initLocationManager]; // call the method to update the user location information [self. locationM startUpdatingLocation];} // create CLLocationManager and start location-(void) initLocationManager {// create a CLLocationManager object and set proxy self. locationM = [[CLLocationManager alloc] init]; self. locationM. delegate = self; // sets the minimum distance between positioning accuracy and location update. locationM. distanceFilter = 100; self. locationM. desiredAccuracy = kCLLocationAccuracyBest;} // obtain location information in the corresponding proxy method-(void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray
  
   
*) Locations {CLLocation * location = [locations firstObject]; // before getting the first location/*, make sure to determine whether the current location is valid. If the horizontal precision is less than zero, indicates that the location object can be obtained, but the data is incorrect. */if (location. horizontalAccuracy <0) return; CLLocationCoordinate2D coordinate = location. coordinate; // coordinate CGFloat longpolling = coordinate. longpolling; // longitude CGFloat latitude = coordinate. latitude; // latitude CGFloat altitude = location. altitude; // CGFloat course = location. course; // direction CGFloat speed = location. speed; // speed NSLog (@ "longitude: % f, latitude: % f", longpolling, latitude); NSLog (@ "altitude: % f, direction: % f, speed: % f ", altitude, course, speed); // if real-time location is not required, even if the location service is disabled after use [self. locationM stopUpdatingLocation];}
  
The positioning frequency and positioning accuracy are not the more accurate the better, depending on the actual situation, because the more accurate the performance consumption, the more electricity consumption. After the positioning is successful, it will be called frequently based on the settings locationManager:didUpdateLocations:Each element of the method has one CLLocationReturns an array because a location may contain multiple locations. After the positioning service is used, if real-time monitoring is not required, the positioning service should be immediately disabled to save resources. In addition to the positioning function, you can also call startMonitoringForRegion:Method to monitor the specified region. 1.2 Background positioning:

Select the background mode based on the foregroundLocation updates

2. for positioning after iOS8, use iOS8 and request positioning authorization: foreground authorization:
Configure in the Info. plist File NSLocationWhenInUseUsageDescriptionIs YES
Frontend and backend authorization:
Configure in the Info. plist File NSLocationAlwaysUsageDescriptionIs YES
-(Void) viewDidLoad {[super viewDidLoad]; if (! [CLLocationManager locationServicesEnabled]) {NSLog (@ "the locating service may not be opened yet. Please set it to open! "); Return;} [self initLocationManager]; // if no authorization is available, request the user to authorize CLAuthorizationStatus = [CLLocationManager authorizationStatus]; if (status = kclthorizationstatusnotdetermined) {// request the foreground to locate authorization // [self. locationM requestWhenInUseAuthorization]; // request the front and backend to locate and authorize [self. locationM requestAlwaysAuthorization] ;}// create CLLocationManager and start location-(void) initLocationManager {// create a CLLocationManager object and set proxy self. locationM = [[CLLocationManager alloc] init]; self. locationM. delegate = self; // sets the minimum distance between positioning accuracy and location update. locationM. distanceFilter = 100; self. locationM. desiredAccuracy = kCLLocationAccuracyBest;} // call-(void) locationManager (CLLocationManager *) manager didChangeAuthorizationStatus :( clthorizationstatus) status {switch (status) {case when: // The user hasn't decided {NSLog (@ "User hasn't decided"); break;} case kclthorizationstatusrestricted: // restricted access {NSLog (@ "restricted access"); break ;} case kclthorizationstatusdenied: // call {NSLog (@ "or ") when the location is disabled or the user APP is authorized to never authorize; break;} case kclthorizationstatusauthorizedalways: // obtain the frontend and backend positioning authorization {NSLog (@ "obtain the frontend and backend positioning authorization"); [self. locationM startUpdatingLocation]; break;} case kclthorizationstatusauthorizedwheninuse: // obtain foreground location authorization {NSLog (@ "obtain foreground location authorization"); [self. locationM startUpdatingLocation]; break;} default: break;} // obtain location information in the corresponding proxy method-(void) locationManager :( CLLocationManager *) manager didUpdateLocations :( NSArray
  
   
*) Locations {CLLocation * location = [locations firstObject]; // before getting the first location/*, make sure to determine whether the current location is valid. If the horizontal precision is less than zero, indicates that the location object can be obtained, but the data is incorrect. */if (location. horizontalAccuracy <0) return; CLLocationCoordinate2D coordinate = location. coordinate; // coordinate CGFloat longpolling = coordinate. longpolling; // longitude CGFloat latitude = coordinate. latitude; // latitude CGFloat altitude = location. altitude; // CGFloat course = location. course; // direction CGFloat speed = location. speed; // speed NSLog (@ "longitude: % f, latitude: % f", longpolling, latitude); NSLog (@ "altitude: % f, direction: % f, speed: % f ", altitude, course, speed); // if real-time location is not required, even if the location service is disabled after use [self. locationM stopUpdatingLocation];}
  

Iv. Geographic code

The locating service also containsCLGeocoderClass, used to process geocode and inverse geocode functions.
* Geographic code: determines geographical coordinates (longitude and latitude) based on the given location (usually the place name ).
[Location-> geographic coordinates]
* Inverse geographic code: you can determine the location information (street, street, and Portal) based on geographical coordinates (longitude and latitude ).
[Geographic coordinates-> location]

-(Void) viewDidLoad {[super viewDidLoad]; self. geocoder = [[CLGeocoder alloc] init]; [self getCoordinateByAddress: @ "Beijing"]; [self getAddressByLatitude: 39.54 longpolling: 116.28];} # pragma mark determines geographic coordinates based on geographical names-(void) getCoordinateByAddress :( NSString *) address {// geocode [self. geocoder geocodeAddressString: address completionHandler: ^ (NSArray * placemarks, NSError * error) {// obtain the first landmark. The landmark stores detailed address information. Note: A single place name may search for multiple addresses CLPlacemark * placemark = [placemarks firstObject]; CLLocation * location = placemark. location; // location CLRegion * region = placemark. region; // region NSDictionary * addressDic = placemark. addressDictionary; // detailed address information dictionary NSLog (@ "location: % @, region: % @, details: % @", location, region, addressDic);}];} # pragma mark obtains the place name (void) getAddressByLatitude :( CLLocationDegrees) latitude longpolling :( CLLocationDegrees) longpolling {// anti-geographic code CLLocation * location = [[CLLocation alloc] initWithLatitude: latitude longpolling: longpolling]; [self. geocoder handle: location completionHandler: ^ (NSArray * placemarks, NSError * error) {CLPlacemark * placemark = [placemarks firstObject]; NSLog (@ "details: % @", placemark. addressDictionary);}];}
Landmarks CLPlacemarkIt also contains the following information:
NSString * name = placemark. name; // name NSString * thoroughfare = placemark. thoroughfare; // The street NSString * subThoroughfare = placemark. subThoroughfare; // Street information, such as NSString * locality = placemark. locality; // city NSString * subLocality = placemark. subLocality; // city information, such as the landmark NSString * administrativeArea = placemark. administrativeArea; // state NSString * subAdministrativeArea = placemark. subAdministrativeArea; // other administrative region information NSString * postalCode = placemark. postalCode; // zip code NSString * ISOcountryCode = placemark. ISOcountryCode; // country Code NSString * country = placemark. country; // country NSString * inlandWater = placemark. inlandWater; // water source, Lake NSString * ocean = placemark. ocean; // ocean NSArray * areasOfInterest = placemark. areasOfInterest; // associated or stakeholder landmark
In the next section, I will write notes related to map-type MapKit. Please wait! If you have any questions, please refer to the comment area below!

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.