iOS system latitude to Baidu longitude and latitude and longitude transfer address

Source: Internet
Author: User

In the ongoing project has such a demand: positioning to obtain the current latitude and longitude, and then use the Baidu Place API using latitude to query the surrounding information. There is no need to display the map, just locate it. It seems that the idea is smooth, but not easy to do.

The latitude and longitude coordinates obtained by the iphone's GPS positioning (Cllocationmanager) are based on the WGS-84 coordinate system (world standard), and Google Maps uses the GCJ-02 coordinate system (Chinese-featured Mars coordinate system), That's why the latitude and longitude coordinates you get are offset on Google Maps. I project demand is the use of Baidu Place API, Baidu's latitude and longitude coordinates on the basis of GCJ-02 and then made a second encryption, is the DB-09 coordinate system. Just want to use the Baidu map of the iOS SDK, the coordinate system is consistent without conversion, because do not want to make the project too big, so there is no use of Baidu SDK, so a way out.

Search on the Internet, there is a ready-made Baidu interface conversion coordinates, through the test from WGS-84 to GCJ-02, and then to DB-09, after two conversion, smooth access to the current correct geographical location information and surrounding information, of course, the information is from Baidu.

ZYLocationManager.h

#import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import "Singleton.h" typedef void (^locationblock) (cllocationcoordinate2d coor); typedef void (^addressblock) (NSString *address); @interface Zylocationmanager:nsobjectsingleton_interface (Zylocationmanager)/** *  get the longitude and latitude after correcting (Baidu map latitude and longitude) */-(void) Getlocationcoordinate: (locationblock) locaiontblock;/** *  to obtain the longitude and latitude after rectification (Baidu map latitude and longitude) and address */-(void) Getlocationcoordinate: (locationblock) Locaiontblock address: (AddressBlock) AddressBlock; @end

Zylocationmanager.m

#import "ZYLocationManager.h" #import "AFNetworking.h" #define Ios_version [[Uidevice currentdevice].systemversion Floatvalue] @interface Zylocationmanager () <cllocationmanagerdelegate>{//save block Locationblock _locationBlock    ; AddressBlock _addressblock;} @property (nonatomic, strong) Cllocationmanager *lm; @end @implementation zylocationmanagersingleton_implementation (        Zylocationmanager)/** * Lazy load */-(Cllocationmanager *) lm{if (!_lm) {_lm = [[Cllocationmanager alloc] init];        _lm.delegate = self;        Positioning accuracy _lm.desiredaccuracy = kcllocationaccuracybest;    repositioning distance _lm.distancefilter = 1000.0f; } return _LM;}    /** * class is called when first used */+ (void) initialize{Zylocationmanager *manager = [self sharedzylocationmanager];        iOS8 need to request permission to the user if (Ios_version >= 8.0) {[Manager.lm requestwheninuseauthorization];    [Manager.lm requestalwaysauthorization]; }//start positioning [Manager.lm startupdatinglocation];} #pragma mark-cLlocationmanager proxy method for obtaining latitude and longitude-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *)    locations{cllocation *location = [locations Lastobject];    Cllocationcoordinate2d coor = location.coordinate;//NSLog (@ "Latitude:%.6f longitude%.6f", Coor.latitude, Coor.longitude);    NSString *x1 = [NSString stringwithformat:@ "%f", Coor.longitude];    NSString *y1 = [NSString stringwithformat:@ "%f", Coor.latitude]; http://api.map.baidu.com/ag/coord/convert?from=0&to=2&x=113.377346&y=23.132648 __block                            Nsdictionary *dict1 = @{@ "from": @ "0", @ "to": @ "2", @ "x": x1,    @ "y": y1};    Afhttprequestoperationmanager *romanager = [Afhttprequestoperationmanager manager]; 1, iOS system by latitude (international standard) to Google latitude and longitude [romanager get:@ "Http://api.map.baidu.com/ag/coord/convert" Parameters:dict1 success:^ ( Afhttprequestoperation *operation, id responseobject) {__block nsstring *resuLtX = [Self base64decode:responseobject[@ "x"]];        __block NSString *resulty = [self base64decode:responseobject[@ "y"]];                  Dict1 = @{@ "from": @ "2", @ "to": @ "4", @ "x": Resultx, @ "y": resulty                }; 2, Google latitude and longitude to Baidu latitude and longitude [romanager get:@ "Http://api.map.baidu.com/ag/coord/convert" Parameters:dict1 success:^ (Afhttpreque            Stoperation *operation, id responseobject) {resultx = [self base64decode:responseobject[@ "x"]];            Resulty = [self base64decode:responseobject[@ "y"]];            Cllocationcoordinate2d Resultcoor = Cllocationcoordinate2dmake ([resulty floatvalue], [ResultX floatValue]);            Assign a value of if (_locationblock) {_locationblock (Resultcoor) to the block;        } [self Getaddresswithcoordinate:resultcoor];        } failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "%@", error);    }]; } failure:^ (afhttprequEstoperation *operation, Nserror *error) {NSLog (@ "%@", error);        }]; Stop positioning [SELF.LM stopupdatinglocation];} -(void) Getlocationcoordinate: (locationblock) locaiontblock{_locationblock = Locaiontblock;} -(void) Getlocationcoordinate: (locationblock) Locaiontblock address: (addressBlock) addressblock{_locationblock =    Locaiontblock; _addressblock = AddressBlock;} #pragma mark-base64 decryption-(NSString *) Base64decode: (NSString *) str{//1, encrypted string to binary data nsdata *data = [[NSData alloc] I    Nitwithbase64encodedstring:str Options:nsdatabase64decodingignoreunknowncharacters]; 2. Binary data to string return [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];} #pragma mark-latitude-Longitude to address-(void) Getaddresswithcoordinate: (cllocationcoordinate2d) coor{if (Coor.latitude = = 0 | | coor.long        Itude = = 0) return;    Cllocation *loca = [[Cllocation alloc] InitWithLatitude:coor.latitude longitude:coor.longitude];    Clgeocoder *geocoder = [[Clgeocoder alloc] init]; [Geocoder Reversegeocodelocation:loca completionhandler:^ (Nsarray *placemarks, Nserror *error) {if (Placemarks.count = = 0 | |                Error) return;        Clplacemark *pm = [Placemarks lastobject];        if (_addressblock) {_addressblock (pm.thoroughfare); }    }];} @end


After IOS8, the request for location requires permission, codeZYLOCATIONMANAGER.M has been written, but it also needs to be added in Info.plist, two properties nslocationalwaysusagedescription and Nslocationwheninuseusagedescription , the attribute value is the information you need to prompt to the user, as shown in:


drag ZYLocationManager.h and zylocationmanager.m into the project, you can directly call the ZYLocationManager.h defined two methods, get to Baidu latitude and longitude and address.

iOS system latitude to Baidu longitude and latitude and longitude transfer address

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.