OC----GPS Positioning

Source: Internet
Author: User

  1. Create a new empty project first 2. Building a rootviewcontroller of succession and Uiviewcontroller

  2. The code is as follows:

  3. //set root view manager-  (BOOL) application: (uiapplication  *) Application didfinishlaunchingwithoptions: (nsdictionary *) launchoptions {     self.window = [[uiwindow alloc] initwithframe:[[uiscreen mainscreen]  bounds]];        rootviewcontroller *rvc = [[ rootviewcontroller alloc] init];    uinavigationcontroller *nav =  [[UINavigationController alloc] initWithRootViewController:rvc];     self.window.rootviewcontroller = nav;         self.window.backgroundcolor = [uicolor whitecolor];    [self.window  Makekeyandvisible];    return yes;} 
  4.  
  5. #import   "RootViewController.h" #import  <CoreLocation/CoreLocation.h> #define  path @ " Http://api.map.baidu.com/geocoder?output=json&location=%f,%f&key=dc40f705157725fc98f1fee6a15b6e60 "@ interface rootviewcontroller  () <CLLocationManagerDelegate>{    //lbs  Location management     cllocationmanager *_manager;} @property   (nonatomic,strong) cllocationmanager *manager; @end @implementation rootviewcontroller-   (void) viewdidload {    [super viewdidload];     self.navigationitem.leftbarbuttonitem = [[uibarbuttonitem alloc] initwithtitle:@ "Start positioning"  style:uibarbuttonitemstyleplain target:self action: @selector (beginelocation)];     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]  initwithtitle:@ "Stop positioning"  style:uibarbuttonitemstyleplain target:self action: @seLector (endlocation)];        //Create manager     [self  initlocationmanager];} /* kcllocationaccuracybestfornavigation //accuracy of  kcllocationaccuracybest;//when navigating with high accuracy   kcllocationaccuracynearesttenmeters; 10m in  kCLLocationAccuracyHundredMeters;100m  kcllocationaccuracykilometer;1000m kcllocationaccuracythreekilometers; 3000m */-  (void) initlocationmanager {    //Lazy Load     if  (!self.manager)  {         //instantiating a Management object          self.manager = [[cllocationmanager alloc] init];         //setting accuracy   accuracy the higher the power consumption         self.manager.desiredaccuracy =  kcllocationaccuracybestfornavigation;        //Precision Size  1m         self.manager.distancefilter = 1;                 /*          After iOS8   need to set up configuration file                    1. Adding   Privacy - Location Usage Description  in Info.plist  ,  nslocationalwaysusagedescription         2. In the Code   [_manager requestAlwaysAuthorization];          //ios8 unique, requesting user authorization to use geo-location information                   */        cgfloat version = [[[ uidevice currentdevice] systemversion] floatvalue];         //Judge version         if  (version >= 8.0)  {             //requesting user authorization to use geo-location information              //authorization the meaning of the authorization              [self.manager requestalwaysauthorization];        }         //if you want to   get location   then you need to set the proxy          self.manager.delegate = self;    }}-  (void) beginelocation  {    //Support for Location Services     if  ([cllocationmanager  Locationservicesenabled])  {        //start positioning          [self.manager startUpdatingLocation];    }else{          NSLog (@ "no GPs"),     }}//stop positioning-  (void) endlocation {    [ Self.manager stopupdatinglocation];} #pragma  mark - cllocationmanagerdelegate protocol//When positioning starts   position changes   will always call//will position the location   put  locations array//This array actually has only one element-  (void) Locationmanager: (cllocationmanager *) manager  Didupdatelocations: (nsarray *) Locations {    nslog (@ "anchor position");     if  (Locations.count) There is only one element in the  {        //array          CLLocation *location = [locations lastObject];         //cllocationcoordinate2d is a structure   internal storage is latitude and longitude          CLLocationCoordinate2D coordinate = location.coordinate;         nslog (@ "longitude:%f", coordinate.longitude);    &nbsP;    nslog (@ "latitude:%f", Coordinate.latitude);          #if  1        //'s official own geo-coding          CLGeocoder *geoCoder = [[CLGeocoder alloc] init];         //geo-coding    geo-coding   (converting latitude to true address location)          [geocoder reversegeocodelocation:location completionhandler:^ (NSArray * Placemarks, nserror *error)  {             //callback This block            //will be put in   after parsing well placemarks  Array (actually an element)             for  (Clplacemark *mark in placemarks)  {                  nslog (@ "name->%@", Mark.name);                 nslog (@ "country:%@", Mark.country);                 for  (nsstring *key in  Mark.addressdictionary)  {                     nslog (@ "%@", Mark.addressdictionary[key]);                 }             }        }];          #else         //Asynchronous Download data   use Baidu's geo-coding         dispatch_async (Dispatch_get_global_queue (DISPATCH_QUEUE_ priority_default, 0),  ^{            nsstring *url = [nsstring  stringwithformat:path,coordinate.latitude, coordinate.longitude];             nsdata *data = [nsdata datawithcontentsofurl:[nsurl  urlwithstring:url]];            //Download Complete              nsdictionary *dict = [ nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:nil];             NSDictionary *result =  dict[@ "Result"];            nslog (@ "addr:%@", result[@ "Formatted_address"]);                     }); #endif             }}/* {  "status": "OK",   "Result":{  "location":{  "LNG":113.675911,  "lat":34.772749 },  "formatted_address ":" Zhengzhou Jinshui District, Henan Province, eight 26th ", " Business ":" Sheng Gang, by eight, gold waterway ", " Addresscomponent ":{ " City ":" Zhengzhou ", " Direction ":" Near ", " Distance ":" ", " District ":" Jinshui ", " province ":" Henan Province ", " Street ":" By Eight ",   "Street_number": "Number 26th"  },  "Citycode":268 } } */-  (void) Locationmanager: ( cllocationmanager *) Manager didfailwitherror: (nserror *) error {     NSLog (@ "failed to locate");} -  (void) didreceivememorywarning {    [super didreceivememorywarning];     // dispose of any resources that can be recreated.} @end

OC----GPS 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.