Ios-senior20-map positioning

Source: Internet
Author: User

Positioning function:

Positioning is a very common feature, such as some map software opened after the user allows the software to locate, then open the software will automatically lock to the current location, if the user mobile phone, then the current location will change as well. To implement functionality requires the use of the Cllocationmanager class in Corelocation, first look at some of the main methods and properties:

Class method:

1.+ (BOOL) locationservicesenabled;

Description: Whether to enable location services, usually if the user does not have location services enabled, you can alert the user to open Location services.

2.+ (clauthorizationstatus) authorizationstatus;

Description: Location Service Authorization status, return enumeration type

kclauthorizationstatusnotdetermined: User has not made a decision whether to enable location services

Kclauthorizationstatusrestricted: The user is not authorized to use location services, and may not have their own forbidden access rights

Kclauthorizationstatusdenied: The user has explicitly banned the application of location services or the current system location service is turned off

Kclauthorizationstatusauthorizedalways: App is authorized to use location services all the time, even if the app is not turned off

Kclauthorizationstatusauthorizedwheninuse: Allow access to location services during use of this application

Property:

1.distanceFilter

Description: Location information updates the minimum distance, only the move is greater than this distance to update the location information, the default is Kcldistancefilternone: No distance restrictions

2.desiredAccruacy

Description: Positioning precision, enumeration type:

Kcllocationaccuracybest: The most accurate positioning
Cllocationaccuracy kcllocationaccuracynearesttenmeters: 10 m error Range
Kcllocationaccuracyhundredmeters: Hundred meters error Range
Kcllocationaccuracykilometer: km Error range
Kcllocationaccuracythreekilometers: 3-kilometer Error Range

Object method:

1.startUpdatingLocation

Description: Start location tracking and will be executed according to the user's set update frequency after starting the location -(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (nsarray *) locations; Method Feedback Positioning Information

2.stopUpdatingLocation

Description: STOP location tracking

3.startUpdatingHeading

Description: Start navigation direction tracking

4.stopUpdatingHeading

Description: Stop navigation direction tracking

5.startMonitoringForRegion Description: Begins a tracking of an area and begins positioning a region. If a user enters or walks out of an area, it calls -(void) Locationmanager: (Cllocationmanager *) Manager didenterregion: ( Clregion *) region and -(void) Locationmanager: (Cllocationmanager *) Manager didexitregion :(clregion*) Region Proxy method feedback related information

6.stopMonitoringForRegion

Description: Stop location tracking for an area

7.requestWhenInUseAuthorization

Note: To request a location service authorization when the app is used, be aware that you need to configure nslocationwheninuseusagedescription in Info.plist before using this method

8.requestAlwaysAuthorization

Description: The request to obtain an app has been using Location services Licensing, note that you need to configure nslocationalwaysusagedescription in Info.plist before using this method

Proxy method:

1.-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) locations;

Description: Execution after the position has changed (it will also be performed after the first position to a location)

2.-(void) Locationmanager: (Cllocationmanager *) Manager
Didupdateheading: (clheading *) newheading;

Description: The navigation direction is changed after the execution

3.-(void) Locationmanager: (Cllocationmanager *) Manager
Didenterregion: (Clregion *) region

Description: Executes after entering an area

4.-(void) Locationmanager: (Cllocationmanager *) Manager
Didexitregion: (Clregion *) region

Description: Execute after exiting an area

Source:

First step: The header file to be introduced into the library

#import <CoreLocation/CoreLocation.h>

Compliance Agreement:<cllocationmanagerdelegate>

Cllocationmanager for managing positioning in the Corelocation framework

@property (Nonatomic,strong) Cllocationmanager *manager;

The Clgeocoder in the Corelocation framework can be encoded and deserialized

Coding and anti-coding classes

@property (Nonatomic,strong) Clgeocoder *gencoder;

-(void) Viewdidload {

[Super Viewdidload];

Steps to locate

First step: Initialize the location manager

Self.manager = [[Cllocationmanager alloc] init];

Step two: Make privacy judgments and authorize

if (![ Cllocationmanger locationservicesenabled]) {

NSLog (@ "Whether to go to privacy settings allow location");

}

When the status is not allowed to access the location service, open the

if ([Cllocationmanager authorizationstatus]! = kclauthorizationstatusauthorizedwheninuse) {

Request authorization

[Self.manager requestwheninuseauthorization];

}

Step three: Set agent and related properties for manager

Self.manager.delegate = self;

Set accuracy (with error 100 m)

self.manager.desiredAccuracy = 100;

Set minimum update distance

Self.manager.distanceFilter = 100;

Fourth step: Turn on positioning

[Self.manager startupdatinglocation];

################ #编码和反编码 ##################

Initializing objects

Self.gencoder = [[Clgencoder alloc] init];

Get latitude and longitude according to place names

[Self getcoordinatebyaddress:@ "Beijing"];

Anti-coding of place names according to latitude and longitude

[Self getaddressbylongitude:113 latitude:23];

Calculate the distance between two places

[Self distance];

}

#pragma mark-distance

-(void) Distance {

Create Location 1

Cllocation *locationbeijing = [[Cllocation alloc] initwithlatitude:40 longitude:116];

Create Location 2

Cllocation *locationdalian = [[Cllocation alloc] initwithlatitude:39 longitude:121];

Cllocation distance = [locationbeijing Distancefromlocation:locationdalian];

NSLog (@ "distance from Beijing to Dalian:%f", distance);

}

#pragma mark-Get relevant information according to the place name

-(void) Getcoordinatebyaddress:(NSString *) address {

Encoding method

[Self.geocoder geocodeaddressstring:address Completionhandler: ^ (nsarray <clplacemark *>*_Nullable Placemarks, Nserror *_nullable error) {

Take the first position (the location of the landmark) based on the returned landmark

Clplacemark *mark = Placemarks.firstobject;

Get location based on landmarks

Cllocation *location = mark.location;

Get Zones from location

Clregin *region = mark.region;

Get dictionary Information

Nsdictionary *addressdic = mark.addressdictionary;

NSString *name=placemark.name;//Place Name
NSString *thoroughfare=placemark.thoroughfare;//Street
NSString *subthoroughfare=placemark.subthoroughfare; Street-related information, such as house numbers, etc.
NSString *locality=placemark.locality; City
NSString *sublocality=placemark.sublocality; City-related information, such as iconic buildings
NSString *administrativearea=placemark.administrativearea; State
NSString *subadministrativearea=placemark.subadministrativearea; Other administrative Area information
NSString *postalcode=placemark.postalcode; Zip
NSString *isocountrycode=placemark. Isocountrycode; Country code
NSString *country=placemark.country; Countries
NSString *inlandwater=placemark.inlandwater; Water, lakes
NSString *ocean=placemark.ocean; Ocean
Nsarray *areasofinterest=placemark.areasofinterest; Associated or interest-related landmarks

NSLog (@ "landmark location%@, area%@, location information%@", location,mark,addressdic);

}];

}

#pragma mark-to de-encode

-(void) Getaddressbylongitude: (clloctiondegrees) Longitude Latitude: (cllocationdegrees) Latitude {

Anti-coding

Cllocation *location = [[Cllocation alloc] Initwithlatitude:latitude longitude:longitude];

[Self.geocoder revergeocoderlocation:location completionhandle:^ (nsarray <clplacemark *>*_Nulable Placemarks, Nserror *_nullable error) {

Nsdictionary *dic = placemarks.firstObject.addressDictionary;

NSLog (@ "anti-coding geo-location information:%@", DIC);

}];

}

Proxy methods for #pragma mark-cllocationmanagerdelegate

This proxy method searches for location information after successful positioning, as long as the minimum distance of the move setting starts to execute this method

-(void) Locationmanager: (Cllocationmanager *) Manager didupdatinglocations: (Nsarray <cllocation *>*) Locations {

Get the last position

Cllocation *location = Locations.lastobject;

Get location coordinates

cllocationcoordinate2d coordinate = location.coordinate;

/* Note :

1. The positioning frequency and positioning accuracy should not be more accurate and better, depending on the actual situation, because the more accurate the more cost-performance, the more electricity.

2. If the positioning is successful, it will be called frequently according to the settings-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations method, This method returns an array of geo-location objects, each of which represents the location information (including longitude, latitude, poster, walking speed, and so on) and returns the array because sometimes a location point may contain multiple locations.

3. If you do not need real-time monitoring after using location services, you should immediately turn off location services to conserve resources.

4. In addition to providing positioning capabilities, Cllocationmanager can also call the Startmonitoringforregion: method to monitor the specified area.

*/

NSLog (@ "Longitude%f, Latitude%f, elevation%f, navigation direction%f, Speed%f", Coordinate.longitude,coordinate.latitude,location.altitude,location.course , location.speed);

In order to save power, if the positioning is not applicable, the positioning must be turned off

[Self.manager stopupdatinglocation];

}

Failed to locate

-(void) Locationmanager: (Clloctionmanager *) Manager didfailwitherror: (nserror *) Error {

}

Ios-senior20-map positioning

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.