The location of iOS development to obtain the current latitude and longitude, and then obtain specific address (city and Province Streets)

Source: Internet
Author: User


Foreword: When doing iOS project today, need to be positioned to get the name of the current city. Baidu Maps SDK has this function, but in order to not rely on a third party, here I use iOS with the framework corelocation to achieve this requirement. IOS8 out, for positioning needs a little more processing, can be normal positioning, this will be at the end of the article to supplement, in the statement before the part is the default iOS7 processing.

First, we need to import the Corelocation system framework into the project. The header file is then introduced into our controller.

#import <CoreLocation/CoreLocation.h>

Then, a Cllocationmanager object is declared as a member variable for locating the latitude and longitude coordinates and complying with the Protocol Cllocationmanager protocol.

@interface Tyviewcontroller () <CLLocationManagerDelegate> {
Cllocationmanager *_locationmanager;
}

Implement the Proxy method.

-(void) Locationmanager: (Cllocationmanager *) Manager didupdatetolocation: (cllocation *) newlocation fromlocation: ( Cllocation *) oldlocation
{
Show longitude to label
Self.longitude.text = [NSString stringwithformat:@ "%lf", NewLocation.coordinate.longitude];
The latitude reality to the label
Self.latitude.text = [NSString stringwithformat:@ "%lf", NewLocation.coordinate.latitude];

Get the name of the city you are currently in
Clgeocoder *geocoder = [[Clgeocoder alloc] init];
To compile the address information according to the latitude and longitude of the reverse geography
[Geocoder reversegeocodelocation:newlocation completionhandler:^ (Nsarray *array, Nserror *error) {
if (Array.count > 0) {
Clplacemark *placemark = [array objectatindex:0];
Display all the information you get to the label
Self.location.text = Placemark.name;
Get the city
NSString *city = placemark.locality;
if (!city) {
The urban information of the four municipalities cannot be obtained through locality, only by acquiring the provincial method (if the city is empty, it is known as the municipality).
City = Placemark.administrativearea;
}
NSLog (@ "city =%@", city);
_citylable.text = City;
[_citybutton settitle:city Forstate:uicontrolstatenormal];
}
else if (Error = = Nil && [array count] = 0)
{
NSLog (@ "No results were returned.");
}
else if (Error!= nil)
{
NSLog (@ "An error occurred =%@", error);
}
}];
The system keeps updating the data until it chooses to stop the update, because we only need to get a latitude and longitude, so we stop the update after we get it.
[Manager Stopupdatinglocation];
}

Finally, the locator manager is initialized in Viewdidload.


-(void) viewdidload
{
[Super Viewdidload];
[Self initializelocationservice];
Do no additional setup after loading the view.
}
-(void) Initializelocationservice {
Initializing the location Manager
_locationmanager = [[Cllocationmanager alloc] init];
Set up agents
_locationmanager.delegate = self;
Set positioning accuracy to M
_locationmanager.desiredaccuracy = Kcllocationaccuracybest;
Set Filter to None
_locationmanager.distancefilter = Kcldistancefilternone;
Start positioning
[_locationmanager startupdatinglocation];
}

Next compile and run the program, manually configure the location coordinates on the iOS simulator, you can print out the latitude and longitude coordinates corresponding to the city name (true machine can directly print out the current city name).

The Clplacemark class encapsulates a number of geographic information attributes, including complete addresses (large to national, small to street) and geographical names, etc., which can be used as appropriate.

PS: If the location of the street information for English, then please deal with localization, while the simulator to adjust the language for Chinese.

The following are supplementary to IOS8:


If normal positioning is required, the IOS8 needs to handle two additional locations relative to iOS7.

1. Add two fields to the plist file of the project: Nslocationalwaysusagedescription,
The Nslocationwheninuseusagedescription,type type is string, the value can be filled (or not filled) according to your needs, and the contents will be displayed in the alert content that the app prompts the user for permission to locate. Specific effects can be tested on your own, there is no additional screenshot.

2. Call the positioning method before the need to call a function, directly in the above IOS7 initialization positioning service method inside the modification can be as follows:


-(void) Initializelocationservice {
//initialization locator Manager
_locationmanager = [[Cllocationmanager alloc] init];
Set proxy
_locationmanager.delegate = self;
//Set positioning precision to M
_locationmanager.desiredaccuracy = Kcllocationaccuracybest;
//Set filter to none
_locationmanager.distancefilter = Kcldistancefilternone
//start positioning
//Get location permission, there are two methods, Depending on your location usage
//One is requestalwaysauthorization, one is requestwheninuseauthorization
[_locationmanager requestalwaysauthorization];//This sentence iOS8 the above version use.
[_locationmanager startupdatinglocation];
}
This requires a real machine test, because it will not use the Apple phone screenshots, so it is not on the effect of the map, if you are interested in the code can be copied directly use, run a look at the effect.

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.