IOS Baidu map Get location name

Source: Internet
Author: User

at present, a lot of applications are used in the Baidu map this version, but some of the methods I did not find on the Internet, but this does not mean that there is no relevant article introduction, then here I record is Baidu map to obtain geographical location, as well as provinces, cities, regions, and other not to say, directly into the topic:

Create a map base layer

First, you need to download the entire content to the Http://dev.baidu.com/wiki/imap/index.php?title=iOS platform/related download, including documentation, sample code, and development packages.

Then get their own API KEY, the specific method according to Baidu's official website application on the line, relatively simple.

The downloaded file should have three

Drag the Inc folder into the project, introduce the header file, and then if you use the real machine to drag the. A file inside the Release-iphoneos to the project, don't forget to drag in the Mapapi.bundle file, and the image of the route node and Pushpin comes from the package.

In addition to introduce Corelocation.framework and quartzcore.framework, so the introduction of work is done, but it is important to note that the static library with objectc++ implementation, There is therefore a need to ensure that there is at least one. mm suffix source file in the project (you can rename any. m suffix file to. mm), or specify the compilation method in the project properties, and Edit Active Target--build-- > Gcc4.2–language, Compile Sources as is set to "objective-c++".

After practice, I recommend not to do so, the default is based on the file type to choose the way to compile, the file if. M with Objective-c, if. MM is objective-c++, manual change will make the whole project with a compile method, is prone to error or incompatible, For example, when the Navigationitem instantiation will be wrong, since Baidu map so maverick, then the best way is to change the map-related classes to. mm, the other is still, so only this class will be compiled with objective-c++.

Show Map

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {//to use Baidu Map, please start Baidumapmanager_mapmanager=[[Bmkmapmanager alloc]init]; //If you want to focus on network and authorization validation events, set the Generaldelegate parameterBOOL ret= [_mapmanager Start:@"c5dcebf3f591fcb69ee0a0b9b1bb4c948c3fa3cc"Generaldelegate:nil]; if(!ret) {NSLog (@ "Manager start failed!"); } Self.window=[[[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease]; //Override point for customization after application launch.Self.viewcontroller=[[[ Viewcontroller alloc] initwithnibname:@ "Viewcontroller" Bundle:nil] autorelease]; Self.window.rootViewController=Self.viewcontroller;    [Self.window makekeyandvisible]; returnYES; }

Of course, this is just a preparation, and it's not possible to have the map layer show up:

// Create a map    of Baidu Mymapview=[[bmkmapview Alloc] Initwithframe:cgrectmake (0, width,height--64 )];    [Mymapview Setmaptype:bmkmaptypestandard];    Mymapview. delegate= self;    Mymapview.zoomlevel=+; // Map Level    Mymapview.showsuserlocation=yes; // can display user location    [Self.view Addsubview:mymapview];

After these words have been written, the map will be able to display normally, but it is worth noting that the key value, many times because of the key value causes the map to not display properly!

After the map is used, remember to release it, otherwise it will affect the memory management system:

-(void) Viewwillappear: (BOOL) Animated {[Btnback sethidden:no];    [Btnaddresstype Sethidden:no];    [Mymapview Viewwillappear]; Mymapview.Delegate= self;//Remember to set nil when not in use, otherwise affect the release of memory_search.Delegate=self;//Bmksearch's agreement}-(void) Viewwilldisappear: (BOOL) Animated {[Btnback sethidden:yes];    [Btnaddresstype Sethidden:yes];    [Mymapview Viewwilldisappear]; Mymapview.Delegate= nil;//when not in use, place nil_search.Delegate=Nil;}

Once the layer is displayed successfully, the next step is to get the name of the address location. To put it simply, anti-geocoding:

//Start Positioning-(void) Mapviewwillstartlocatinguser: (Bmkmapview *) mapview{NSLog (@"Start Positioning");}/** * After the user location is updated, this function is called * @param mapview map view * @param userlocation New User Location*/-(void) Mapview: (Bmkmapview *) Mapview didupdateuserlocation: (bmkuserlocation *) userlocation{NSLog (@"latitude--%f,longtitude---%f", Userlocation.location.coordinate.latitude,userlocation.location.coordinate.longitude); Localatitude=userlocation.location.coordinate.latitude;//LatitudeLocalongitude=userlocation.location.coordinate.longitude;//accuracyBmkcoordinateregion region; //Center The positioned point in the displayRegion.center.latitude=Localatitude; Region.center.longitude=Localongitude; //Geo -coded geographic locationCllocationcoordinate2d pt= (cllocationcoordinate2d) {0,0}; PT=(cllocationcoordinate2d) {localatitude,localongitude}; BOOL Flag=[_search reversegeocode:pt]; if(flag) {mymapview.showsuserlocation=no;//do not show your locationSelf.btndone.enabled=YES; }        //the scale of the current position callout and map (note is not available)//Bmkcoordinatespan spans;//spans.latitudedelta=0.01;//spans.longitudedelta=0.01;//Region.span=spans;mymapview.region=Region ;}

When using [_search reversegeocode:pt] , it is called a protocol method, which is the following method:

//Anti-geo-coding-(void) Ongetaddrresult: (bmkaddrinfo *) result ErrorCode: (int) error{if(error==0) {bmkpointannotation*item=[[Bmkpointannotation alloc] init]; Item.coordinate=result.geopt;//Geographic coordinatesITEM.TITLE=RESULT.STRADDR;//Geographic name[Mymapview Addannotation:item]; Mymapview.centercoordinate=result.geopt; Self.lalAddress.text=[RESULT.STRADDR stringbyreplacingoccurrencesofstring:@"-"Withstring:@""]; if(! [Self.lalAddress.text isequaltostring:@""]) {strprovince=result.addresscomponent.province;//Provincesstrcity=result.addresscomponent.city;//CityStrdistrict=result.addresscomponent.district;//Area        }//clgeocoder *geocoder=[[clgeocoder alloc] init];//Clgeocodecompletionhandler handle=^ (nsarray *palce,nserror *error) {//For (Clplacemark *placemark in palce) {//NSLog (@ "%@1-%@2-%@3-%@4-%@5-%@6-%@7-%@8-%@9-%@10-%@11-%@12", Placemark.name,placemark.thoroughfare,plac Emark.subthoroughfare,placemark.locality,placemark.sublocality,placemark.administrativearea, Placemark.postalcode,placemark. Isocountrycode,placemark.country,placemark.inlandwater,placemark.ocean,placemark.areasofinterest);//Break ;//            }//        };//cllocation *loc = [[Cllocation alloc] Initwithlatitude:localatitude longitude:localongitude];//[Geocoder reversegeocodelocation:loc completionhandler:handle];    }}

So I get the geographical names, provinces, cities, regions can be successfully displayed, to here, has been done!

However, is there any part of the above code that has been commented out? This part of the code function is also able to get to provinces, cities, regions, but Clgeocoder is the corelocation system in the framework of the positioning, it should be said that Google positioning it, Baidu map latitude and longitude deviation, so the location and the actual location is different. Moreover, the content that theClgeocoder locates has a large part is empty, I have not found the reason, hoped that the friend can solve this trouble for me! Thank you first!

Here, the record is not finished yet! To optimize the effect of the label, look at the following code:

-(Bmkannotationview *) Mapview: (Bmkmapview *) Mapview viewforannotation: (ID<BMKAnnotation>) annotation{//generate reuse Flag identifierNSString *annotationviewid =@"Xidanmark"; //Check if there is a reuse cachebmkannotationview* Annotationview =[Mapview Dequeuereusableannotationviewwithidentifier:annotationviewid]; //The cache does not hit, it constructs a, the general first add annotation code will run here    if(Annotationview = =Nil) {Annotationview=[[Bmkpinannotationview alloc] initwithannotation:annotation Reuseidentifier:annotationviewid]; ((Bmkpinannotationview*) annotationview). Pincolor =bmkpinannotationcolorred; //set the effect of heavy sky Fall (annotation)((bmkpinannotationview*) annotationview). Animatesdrop =YES; }        //Set LocationAnnotationview.centeroffset = Cgpointmake (0,-(AnnotationView.frame.size.height *0.5)); Annotationview.annotation=annotation; //Click Eject Bubble, Pop bubble premise annotation must implement the title propertyAnnotationview.canshowcallout =YES; //Set Whether you can drag and dropAnnotationview.draggable =NO; returnAnnotationview;}

Attach a long press event now!

//map Long Press events-(void) Mapview: (Bmkmapview *) Mapview Onlongclick: (cllocationcoordinate2d) coordinate{//Remove all labels before long pressNsarray *arrayanmation=[[Nsarray alloc] initWithArray:myMapView.annotations];    [Mymapview removeannotations:arrayanmation]; //get latitude and longitudeLocalatitude=Coordinate.latitude; Localongitude=Coordinate.longitude; Cllocationcoordinate2d PT= (cllocationcoordinate2d) {0,0}; PT=(cllocationcoordinate2d) {coordinate.latitude,coordinate.longitude}; BOOL Flag=[_search reversegeocode:pt]; if(flag) {NSLog (@"Success"); }Else{NSLog (@"falied"); }}

What's wrong with the above code, or who has a good suggestion or method, please leave your traces! I hope this blog post can help the vast number of friends!

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.