IOS get current latitude and longitude

Source: Internet
Author: User

In general, the LBS function is generally divided into two pieces, one is geo-positioning, is to obtain the current accuracy, latitude and location of the function, this part of the function is mainly used in Corelocation.frameworks. Part of this is to display the map information, enrich the map content, and so on, this part mainly uses Mapkit.frameworks. The test of these functions is best done on the real machine. The simulator is typically located at Apple's California headquarters. First introduce corelocation. Let's talk about the main features first. The first feature, and also the most basic function, is to get the longitude latitude. Toss the original is the assignment of the wrong posture, frustration feeling really strong AH. Well, to get down to the chase, getting longitude latitude on iOS is fairly straightforward.   Add Corelocation.frameworks and place its header file in the header file of the class that needs to be referenced. Creates a Cllocationmanager object. Sets the proxy for the current Cllocationmanager object. Set other basic properties as follows://Set addressing longitude self.locManager.desiredAccuracy = kcllocationaccuracybest;  Self.locManager.distanceFilter = 5.0; then call-(void) startupdatinglocation; method to begin updating the current coordinate position. So the preparatory work is finished. Then you have to complete the proxy method. If only to achieve the current latitude and longitude of the function, as long as the implementation of the following two agents is good. -(void) Locationmanager: (Cllocationmanager *) manager    didupdatetolocation: (cllocation *) newlocation     Fromlocation: (Cllocation *) oldlocation; -(void) Locationmanager: (Cllocationmanager *) Manager     Didfailwitherror: (Nserror *) error;  The second agent is called when addressing fails. Cheese in the inside to do the corresponding treatment is good. We mainly talk about the first agent. The first proxy method passed to us three parameters, Manager,newlocation and oldlocation. If only the location, as long as care newlocation this is good. We want to be the warpWhere does the degree dimension be placed? Cllocation has a property called @property (ReadOnly, nonatomic) cllocationcoordinate2d coordinate; The information we want is stored here. typedef struct {    cllocationdegrees latitude;    cllocationdegrees longitude;} cllocationcoordinate2d; Cllocationdegrees In fact is a double type, we will be the text of it.   NOTE:. It's good to use startupdatinglocation when using the positioning function for the first time. The system will automatically eject the pop-up window that you are authorized to use. In the second use, determine whether the user opens the location function using the + (BOOL) Locationservicesenabled method to determine that no error is generated. Call Stopupdatinglocation to stop the last request before the request ends or a second request is made. The following attached implementation code://Initialize and start updating      Self.locmanager = [[Cllocationmanager alloc] init];    Self.locManager.delegate = self;    Self.locManager.desiredAccuracy = kcllocationaccuracybest;    Self.locManager.distanceFilter = 5.0;    [Self.locmanager startupdatinglocation]; //Proxy method implementation-(void) Locationmanager: (Cllocationmanager *) Manager didupdatetolocation: (cllocation *) newlocation fromlocation: ( Cllocation *) oldlocation{    Debuglog (@ "%f,%f", newlocation.coordinate.latitude,newlocation.Coordinate.longitude);}  -(void) Locationmanager: (Cllocationmanager *) Manager didfailwitherror: (Nserror *) error{    Debuglog ( @ "%@", error);}    getting location information for your current location requires the use of a new class, Mkreversegeocoder. This class is in Mapkit.framework. We add the framework and import the header file to use. Hit a code, the results found that the class iOS5.0 is not necessary. Really In order to take care of compatibility, we first study mkreversegeocoder, and then to study the new class, well, the name is Clgeocoder, well, not misspelled. Inside the corelocation.  mkreversegeocoder *geocoder = [[Mkreversegeocoder alloc] initwithcoordinate:currentcoordinate2d];      geocoder.delegate = self; [Geocoder start]; After calling the above code, the reverse address encoding API is automatically invoked. We use proxies to receive this. As for the proxy method, we need to implement two. -(void) Reversegeocoder: (Mkreversegeocoder *) Geocoder Didfindplacemark: (Mkplacemark *) placemark {}-(void) Reversegeocoder: (Mkreversegeocoder *) Geocoder didfailwitherror: (Nserror *) error{} The first method is to obtain a reverse-coded. The second is when the reverse encoding fails, the processing error is used. We mainly discuss the first method. Placemark (An object of the Mkplacemark Class) is actually a property of the Geocoder (the object of the Mkreversegeocoder class). From Geocoder inside take placemark this and direct take placemark this actually difference is not big. And the information we need is mostly in this. This dictionary holds the underlying data @property (nonatomic, ReadOnly) nsdictionary *addressdictionary: Let's try to get something out of this dictionary. Here is the dictionary I poured out with this addressdictionary property. Let's look at the analysis. {    City = "\U897F\U5B89\U5E02";//Town name     Country = "\U4E2D\U56FD";//Country name     CountryCode = cn;//Country code     Formattedaddresslines =     (        "\U4E2D\U56FD",        "\u9655\u897f\u7701\u897f\u5b89\u5e02\u96c1\u5854\u533a",        "\u9ad8\u65b0\ U516d\u8def34\u53f7 "   ); This should be the formatted address     state = "\u9655\u897f\u7701"; Province     Street = "\u9ad8\u65b0\u516d\u8def 34\u53f7";//Street Full name     sublocality = "\u96c1\u5854\u533a"; Zone name     Subthoroughfare = "34\U53F7";//specific address     thoroughfare = "\u9ad8\u65b0\u516d\u8def";//Street name}& nbsp; Note: The above dictionary is a dictionary that can be converted directly to a contact, through this abcreatestringwithaddressdictionary property.   The following are other properties of placemark. You can take it at your own discretion. Address dictionary Properties@property (nonatomic, readonly) NSString *name; eg. Apple Inc. @property (Nonatomic, readonly) NSString *thoroughfare; Street address, eg. 1 Infinite loop@property (nonatomic, readonly) NSString *subthoroughfare; eg. 1@property (nonatomic, readonly) NSString *locality; City, eg. Cupertino@property (nonatomic, readonly) NSString *sublocality; Neighborhood, common name, eg. Mission District@property (nonatomic, readonly) NSString *administrativearea; State, eg. Ca@property (nonatomic, readonly) NSString *subadministrativearea; county, eg. Santa Clara@property (nonatomic, readonly) NSString *postalcode; Zip code, eg. 95014@property (nonatomic, readonly) NSString *isocountrycode; eg. Us@property (nonatomic, readonly) NSString *country; eg. States@property (nonatomic, readonly) NSString *inlandwater; eg. Lake Tahoe@property (nonatomic, readonly) NSString *ocean; eg. Pacific Ocean@property (nonatomic, readonly) Nsarray *areasofinterest; eg. Golden Gate park  Note: In the course of my use, I have found that if the network is suspended from death, it may not be able to get adverse results for a long time. This may require attention.  IOS5 is not recommended for use on top of meA whole lot of talking. We need to use this Clgeocoder class. The method of use is also very simple. Refer to the following steps: First create a Clgeocoder object and then call his-(void) Reversegeocodelocation: (cllocation *) Location Completionhandler: ( Clgeocodecompletionhandler) Completionhandler; method. The parameter types are passed as required. Some cheese will ask this clgeocodecompletionhandler how to write something? This is actually IOS4 after the official highly recommended block, will not use the classmate quickly go to see the document it. This is the definition of Clgeocodecompletionhandler. typedef void (^clgeocodecompletionhandler) (Nsarray *placemarks, Nserror *error); All we need to do is write a block object and pass it in.   The following is a reference code that uses Clgeocoder. No agent, is it very happy?     clgeocoder* geocoder = [[Clgeocoder alloc] init];       [Geocoder reversegeocodelocatio N:newlocation completionhandler:     ^ (nsarray* placemarks, nserror* error) {        & nbsp NSLog (@ "%@", Placemarks);     }]; The contents of the positioning section is introduced here, as to what the forward encoding, what is mentioned above rate, distance and so on, we look at the document. It is a good package to look at the document. ,   ios development, if you want to get the current position, just the following steps:    First, import the Corelocation framework into the project and refer to  [plain] View Plaincopy #import        Then, declare implement proxy method,  [plain] ViewPlaincopy@interface locationmanager:nsobject e>       Then, start updating location information:   [plain] View Plaincopylocationmanager = [[Cllocationmanager alloc] init];  locationmanager.delegate = self;   locationmanager.desiredaccuracy = Kcllocationaccuracybest;   locationmanager.distancefilter = Kcldistancefilternone;   [locationmanager Startupdatinglocation];        Locationmanager need to be defined as private or attribute variables. After each location update, cllocationmanagerdelegate-(void) Locationmanager is called: (Cllocationmanager *) Manager didupdatetolocation: ( Cllocation *) newlocation fromlocation: (cllocation *) Oldlocation method, the NewLocation of the method is the current position.     After acquiring the location, if you want to get the geographic information of the current location, you need to use Clgeocoder (Mkreversegeocoder is obsolete).  [plain] View Plaincopyclgeocoder *geocoder = [[Clgeocoder alloc] init];  [geocoder reversegeocodelocation:newlocation completionhandler:^ (Nsarray *array, NSError *error) {       if (Array.count > 0) {          Clplacemark *placemark = [array objectatindex:0];           nsstring *country = Placemark. Isocountrycode;            NSString *city = placemark.locality;       }  }];      Placemark contains geographic information for NewLocation.

IOS gets the current latitude and longitude

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.