IOS Development Guide 16th Chapter Location Services and maps application

Source: Internet
Author: User

1 Location Service encoding

Using the core location framework

Cllocationmanger: Used to locate service management class, can provide us with location information and high information, you can also monitor the device into or out of an area, but also to obtain the direction of operation of the device.

Cllocation: Encapsulates location and height information.

Cllocationmangerdelegate

Preparing: Loading the core location framework

Modify project configuration: Supporting Files-info.pist add nslocationalwaysusagedescription and nslocationwheninuseusagedescription to customize text content.

Initialize Locationmanager and Set properties-set user authorization and modify project configuration-turn on and off-implement delegation

- (void) viewdidload {[Super viewdidload]; //Location Services Management Object InitializationSelf.locationmanager =[[Cllocationmanager alloc] init]; Self.locationmanager.Delegate=Self ;
Set accuracy self.locationManager.desiredAccuracy = kcllocationaccuracybest;
Set the distance filter: Defines the minimum distance to obtain location information after the device is moved, in meters self.locationManager.distanceFilter = 1000.0f; after iOS8, set user authorization. In order to be able to eject the authorization dialog, we need to modify the project configuration. [Self.locationmanager requestwheninuseauthorization]; [Self.locationmanager requestalwaysauthorization]; }

Start positioning and stop positioning:

IOS6 later through Allowdeferredlocationupdatesuntiltraveled:timeout: Deferred updates are implemented, disallowdeferredlocationupdates off delay updates.

The Pauseslocationupdatesautomatically property setting automatically pauses the position update to the system by turning on and off the location service.

-(void) viewwillappear: (BOOL) animated{    [Super viewwillappear:animated];     // start positioning, according to set conditions will continue to request callback new location information, open to be cautious.       [Self.locationmanager startupdatinglocation];} -(void) viewwilldisappear: (BOOL) animated{    [Super viewwilldisappear:animated];     // Stop Positioning      [Self.locationmanager stopupdatinglocation];}

Implement the Delegate method: When the user device moves more than a certain distance, it will callback the delegate method.

Locationmanager:didupdatelocations: Positioning success

Locationmanager:didfailwitherror: Failed to locate

Locationmanager:didchangeauthorizationstatus: Called when authorization status changes

#pragmaThe Mark Core Location delegate method is used to implement updates to locations-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *Locations is a collection of positional changes, stored in the order of time changes {Gets the device's current position cllocation *currlocation = [Locations Lastobject];
Get location information cllocation encapsulates altitude and coordinate (latitude longitude) Self.txtLat.text= [NSString stringWithFormat:@"%3.5f", currLocation.coordinate.latitude]; latitude Self.txtLng.text= [NSString stringWithFormat:@"%3.5f", currLocation.coordinate.longitude]; longitude Self.txtAlt.text= [NSString stringWithFormat:@"%3.5f", currlocation.altitude]; height}- (void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (Nserror *) error{NSLog (@"Error:%@", error);}- (void) Locationmanager: (Cllocationmanager *) Manager didchangeauthorizationstatus: (clauthorizationstatus)status{parameter is authorization information, You can also use Cllocationmanager's static method Authorizationstatus to obtain authorization informationif(Status = =kclauthorizationstatusauthorizedalways) {NSLog (@"Authorized"); } Else if(Status = =kclauthorizationstatusauthorizedwheninuse) {NSLog (@"Authorizedwheninuse"); } Else if(Status = =kclauthorizationstatusdenied) {NSLog (@"Denied"); } Else if(Status = =kclauthorizationstatusrestricted) {NSLog (@"Restricted"); } Else if(Status = =kclauthorizationstatusnotdetermined) {NSLog (@"notdetermined"); } }

2 geo-Information anti-coding

Returns the relevant text description information for a location by geographical coordinates. Implemented by Clgeocoder, this class enables the conversion between geographic coordinates and text-descriptive information.

Method:-reversegeocoderlocation:completionhandler:

Clplacemark: "Landmark" class, encapsulating text description.

A geographic coordinate point refers to a range.

Prepare: Add addressbook.framework, add #import <AddressBook/AddressBook.h> in Viewcontroller

-(Ibaction) Reversegeocode: (ID) Sender {Clgeocoder*geocoder =[[Clgeocoder alloc] init]; Start encoding [geocoder reverseGeocodeLocation:self.currLocation completionhandler: ^ (Nsarray *placemarks, Nserror * Error)                       {After parsing completes the callback, the first parameter is a landmark collection of successful anti-coding, and the second parameter describes the error message. if([Placemarks Count] >0{Determine if the anti-coding is successful Clplacemark*placemark = placemarks[0] Take out the first one, or traverse all; Dictionary of Address information nsdictionary*addressdictionary =placemark.addressdictionary; NSString*address =[addressdictionary objectforkey: (NSString*)Kabpersonaddressstreetkey]; Address = Address = = nil? @ "" : Address; NSString*state =[addressdictionary objectforkey: (NSString*) Kabpersonaddressstatekey]; State= state = = Nil?@"": State; NSString*city =[addressdictionary objectforkey: (NSString*) Kabpersonaddresscitykey]; City= City = = Nil?@"": City; _txtview.text = [NSString stringwithformat:@ "%@ \n%@ \n%@" , State, address,city]; }                                          }];}

3 Geographic Information Code query

The query result is a collection of geographic coordinates that are described by geographical information.

Clgeocoder class

Method: Geocoderaddressdictionary:completionhander: Query by address information Dictionary object parameter

Geocoderaddressstring:completionhander:

GeocoderAddressString:inRegion:completionHandler: through string and range queries, the second parameter is the Clregion class.

-(Ibaction) Geocodequery: (ID) Sender {if(Self.txtQueryKey.text = = Nil | | [Self.txtQueryKey.text length] = =0) {        return; } Clgeocoder*geocoder =[[Clgeocoder alloc] init]; [Geocoder geocodeAddressString:self.txtQueryKey.text completionhandler: ^ (Nsarray *placemarks, Nserror * Error) {NSLog (@"Query record number:%u", (unsignedint) [Placemarks Count]); if([Placemarks Count] >0) { Clplacemark * Placemark = placemarks[0]; Nsdictionary*addressdictionary =placemark.addressdictionary; NSString*address =[addressdictionary objectforkey: (NSString*) Kabpersonaddressstreetkey]; Address= Address = = Nil?@"": Address; NSString*state =[addressdictionary objectforkey: (NSString*) Kabpersonaddressstatekey]; State= state = = Nil?@"": State; NSString*city =[addressdictionary objectforkey: (NSString*) Kabpersonaddresscitykey]; City= City = = Nil?@"": City; cllocationcoordinate2d coordinate = placemark.location.coordinate; NSString* Strcoordinate = [NSString stringWithFormat:@"Longitude:%3.5f \ n Latitude:%3.5f", Coordinate.latitude, Coordinate.longitude]; Self.txtView.text= [NSString stringWithFormat:@"%@ \%@ \n%@ \n%@", Strcoordinate,state, address,city]; //turn off the keyboard[Self.txtquerykey Resignfirstresponder];    }    }]; }

4 Testing for Location services

If you want the simulator to start running, you can set the simulation data in the startup parameters: Edit Scheme-run mylocation.app-options-Set the core location and default location or add a GPX file yourself

Continuous position Change test: Simulator-debug-location The following 3 menu items can emit continuous position change data

IOS Development Guide 16th Chapter Location Services and maps application

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.