Build Baidu maps, walking routes, anti-geocoding applications

Source: Internet
Author: User
Tags bool int size polyline
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions

    {

    //Start engine baidumapmanager

    _mapmanager = [[Bmkmapmanager alloc]init];

    If you want to focus on network and authorization authentication events, set the Generaldelegate parameter, otherwise nil can

    BOOL ret = [_mapmanager start:@ "Valid key for the application" Generaldelegate: (id< bmkgeneraldelegate>) self];

    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];

    return YES;

    }

Create a map with xib or manually

In-(void) Viewwillappear: (BOOL) animated to set the proxy (or create a setting when viewdidload), remember, otherwise the grid may appear without the map.

_mymapview=[[bmkmapview Alloc] Initwithframe:cgrectmake (0, 0, Screen.width, screen.height)];

    [Super viewwillappear:animated];
    [_mapview viewwillappear];
    _mapview.showsuserlocation = no;//First turns off the displayed positioning layer
    _mapview.usertrackingmode = bmkusertrackingmodenone;//Sets the status of the positioning
    _mapview.showsuserlocation = yes;//display positioning layer
      _mapview.delegate = self;
    _geocodesearch.delegate = self;
    _userlocation.delegate = self;
    _walkingrouteplanoption.delegate = self;

Walking route agent, positioning agent and so on.


When you exit the interface (note. cannot be in the Viewwilldisappear method, as for why listen to others said Baidu Map and iOS conflict) set the agent to empty

        [_mapview viewwilldisappear];
        _mapview.delegate = nil;
        _geocodesearch.delegate = nil; Here remember the time need to set nil, otherwise affect the release of memory
        _userlocation.delegate = nil;
        [_userlocation Stopuserlocationservice];
        _mapview.showsuserlocation = NO;
        _walkingrouteplanoption.delegate = nil;

When you use the
/**
 * Open Location Services
 *
/-(void) startuserlocationservice;
, it will callback the proxy method

/**
 * After the user orientation is updated, this function is called
 * @param userlocation New User location */
-(void) Didupdateuserheading: ( Bmkuserlocation *) userlocation;

There are some failures. Stop location and other agent methods please download Baidu SDK view.

-(void) Didupdateuserlocation: (bmkuserlocation *) userlocation{
    NSLog (@ "Latitude--%f,longtitude---%f", Userlocation.location.coordinate.latitude,userlocation.location.coordinate.longitude);
    Cllocationdegrees Localatitude;
    Cllocationdegrees Localongitude;
    localatitude=userlocation.location.coordinate.latitude;//Latitude
    localongitude= userlocation.location.coordinate.longitude;//Jing
    bmkcoordinateregion region;
    Centers the positioned point to display the
    region.center.latitude=localatitude;
    Region.center.longitude=localongitude;
    Region.span.latitudeDelta  = 0.01;
    Region.span.longitudeDelta = 0.01;
    [_mapview setregion:region Animated:no];
    
    Subcoor.latitude = Localatitude;
    Subcoor.longitude = Localongitude;
    [_mapview Setcentercoordinate:subcoor animated:yes];
}

Location can be determined based on the latitude and longitude obtained.

[Self geocode:[_latitude doublevalue] withlongitude:[_longitude Doublevalue]];

-(void) GeoCode: (double) latitude Withlongitude: (double) longitude{
    
    cllocationcoordinate2d pt = ( Cllocationcoordinate2d) {0, 0};
    PT = (cllocationcoordinate2d) {latitude, longitude};
    Bmkreversegeocodeoption *reversegeocodesearchoption = [[Bmkreversegeocodeoption alloc]init];
    Reversegeocodesearchoption.reversegeopoint = pt;
    BOOL flag = [_geocodesearch reversegeocode:reversegeocodesearchoption];
    
    if (flag)
    {
        NSLog (@ "anti-geo retrieval sent successfully");
    }
    else
    {
        NSLog (@ "anti-geo retrieval send Failed");}
}

which
/**
 * Base coordinates get address information
 * Asynchronous function, return the result in bmkgeocodesearchdelegate ongetaddrresult notification
 * @param Reversegeocodeoption Anti-geo Retrieval information class
 * @return successfully returned yes, otherwise no
 */
-(BOOL) Reversegeocode: ( bmkreversegeocodeoption*) reversegeocodeoption;
It then calls
/**
 * Return anti-geocoding search results *
 @param Searcher Search Object
 * @param result search Result
 * @param error error number, @see bmksearcherrorcode< c10/>*/
-(void) Ongetreversegeocoderesult: (Bmkgeocodesearch *) Searcher Result: (Bmkreversegeocoderesult *) Result ErrorCode: (bmksearcherrorcode) error;
is the
-(void) Ongetreversegeocoderesult: (Bmkgeocodesearch *) Searcher Result: (Bmkreversegeocoderesult *) result ErrorCode: ( Bmksearcherrorcode) Error
{
	if (Error = = 0) {
        //
        Self.addarr = [NSString stringwithformat:@ "%@", Result.address];
        _pointannotation.subtitle =[nsstring stringwithformat:@ "Current location:%@", Self.addarr];
        if (_pointannotation = = nil) {
            [xccommonutility qqtshowalertmsg:@ ' cannot get the current position, please try again later];
            return;
        }
        [Annotationarrays addobject:_pointannotation];
        [_mapview addannotations:annotationarrays];
        [Self seachwalkroute];
	}
}

Ps:

Result.address is the location that is obtained for the anti-geocoding. [Annotationarrays addobject:_pointannotation]; is an array of labels. When there are multiple annotations, add the labels to the array before adding them to the

[_mapview Addannotations:annotationarrays]; the end of the article will explain.

/**
 * Adding annotations to the Map window requires implementing the Bmkmapviewdelegate-mapview:viewforannotation: function to generate the view * @param for the callout
 annotation Label to add
 */
-(void) Addannotation: (id <BMKAnnotation>) annotation;

/**
 * Adding a set of annotations to the Map window requires implementing the Bmkmapviewdelegate-mapview:viewforannotation: function to generate the view * @param for the callout
 annotations Array of labels to add
 */
-(void) Addannotations: (Nsarray *) annotations;


Walking route

/**
 * Walking route retrieve
 * Async function, return result in bmkroutesearchdelegate ongetwalkingrouteresult notification
 * @param Walkingrouteplanoption Walk Retrieve Information class
 * @return return Yes, otherwise no */
-(BOOL) Walkingsearch: ( bmkwalkingrouteplanoption*) walkingrouteplanoption;
/**
 * Back to walking search results
 * @param Searcher Search Object
 * @param result search results, type bmkwalkingrouteresult
 * @param error Error number, @see bmksearcherrorcode
 */
-(void) Ongetwalkingrouteresult: (bmkroutesearch*) Searcher Result: ( bmkwalkingrouteresult*) result ErrorCode: (bmksearcherrorcode) error;

Directly on the code

-(void) seachwalkroute{bmkwalkingrouteplanoption *walkingroute = [[Bmkwalkingrouteplanoption alloc]init];
    bmkplannode* CurrentNode = [[Bmkplannode alloc] init];
    currentnode.pt = Miancoor; Currentnode.name = @ "AAA";
    Note that this cannot be empty @ "" bmkplannode* poinode = [[Bmkplannode alloc] init];
    poinode.pt = Subcoor;
    Poinode.name = @ "BBB";//Note that this cannot be empty @ "" Walkingroute.from = CurrentNode;
    walkingroute.to = Poinode;
    BOOL flag = [_walkingrouteplanoption Walkingsearch:walkingroute];
    if (flag = = YES) {NSLog (@ "search succeeded");
        }else{[xccommonutility qqtshowalertmsg:@ "temporarily unable to get the walking route"];
    NSLog (@ "search failed"); }}-(void) Ongetwalkingrouteresult: (bmkroutesearch*) Searcher Result: (bmkwalkingrouteresult*) result ErrorCode: (
	Bmksearcherrorcode) error{nsarray* array = [Nsarray arraywitharray:_mapview.annotations];
	[_mapview Removeannotations:array];
	Array = [Nsarray arraywitharray:_mapview.overlays];
	[_mapview Removeoverlays:array]; if (Error = = bmk_search_no_error) {bmkwalkingrouteline* plan = (bmkwalkingrouteline*) [Result.routes objectatindex:0];
		int size = [Plan.steps count];
		int planpointcounts = 0;
            for (int i = 0; i < size; i++) {bmkwalkingstep* transitstep = [Plan.steps objectatindex:i];
                if (i==0) {mappointannotion* item = [[Mappointannotion alloc]init];
                Item.coordinate = plan.starting.location;
                Item.subtitle =_describe;
                Item.type = 0;
                Item.tagnumber = 1; [_mapview Addannotation:item]; Add Start Callout}else if (i==size-1) {mappointannotion* item = [[Mappointannotion al
                Loc]init];
                Item.coordinate = plan.terminal.location;
                Item.subtitle =[nsstring stringwithformat:@ "Current location:%@", Self.addarr];;
                Item.type = 1;
                Item.tagnumber = 0; [_mapview Addannotation:item]; Add a start markNOTE}//Add annotation node mappointannotion* item = [[Mappointannotion alloc]init];
            Item.coordinate = transitStep.entrace.location;
            Item.title = transitstep.entraceinstruction;
            Item.degree = transitstep.direction * 30;
            Item.type = 4;
            [_mapview Addannotation:item];
        Total number of locus points cumulative planpointcounts + = Transitstep.pointscount;
        }//Locus point bmkmappoint * temppoints = new bmkmappoint[planpointcounts];
        int i = 0;
            for (int j = 0; J < size; J + +) {bmkwalkingstep* transitstep = [Plan.steps objectatindex:j];
            int k=0;
                for (k=0;k<transitstep.pointscount;k++) {temppoints[i].x = transitstep.points[k].x;
                Temppoints[i].y = TRANSITSTEP.POINTS[K].Y;
            i++; }}//Build Bmkpolyline bmkpolyline* polyLine by points = [BMKPolyline polylinewithpoints:temppoints count:planpointcounts]; [_mapview Addoverlay:polyline];
        
	Add route overlay Delete []temppoints; }
}

The second method is basically to copy the official Deom directly behind the original found so convenient. At first, all of their own research, until the drawing of the walking route this piece of work for a long time finally did not get out to copy the demo and then slightly modified minutes to fix it.



The added annotations just mentioned can be used at both ends of the route.

Adding a callout must implement this proxy

/**
 * Generate corresponding View
 * @param mapview map View
 * @param annotation specified callout
 * @return Generated Callout View
 * *
-(Bmkannotationview *) Mapview: (Bmkmapview *) Mapview viewforannotation: (id <BMKAnnotation>) annotation;
-(Bmkannotationview *) Mapview: (Bmkmapview *) Mapview viewforannotation: (id<bmkannotation>) Annotation {
    
    Bmkannotationview *newannotation =[mapview viewforannotation:annotation]; if (newannotation==nil && [Annotation iskindofclass:[mappointannotion class]]) {mappointannotion* poi
        Ntannotation = (mappointannotion*) annotation;
        NSString *annotationviewid = [NSString stringwithformat:@ "iannotation-%d", Pointannotation.tagnumber];
        Newannotation = [[Bmkpinannotationview alloc] initwithannotation:annotation Reuseidentifier:annotationviewid];
        Set color Newannotation.tag = Pointannotation.tagnumber;
        
        ((bmkpinannotationview*) newannotation). Pincolor = Bmkpinannotationcolorpurple;
        Fall from the Sky effect ((bmkpinannotationview*) newannotation). Animatesdrop = NO;
        Settings can be dragged ((bmkpinannotationview*) newannotation). draggable = NO;
            Set the pin icon if (Pointannotation.tagnumber = = 0) {((bmkpinannotationview*) newannotation). Image = [UIImage imagenamed:@ "Map_mark_mylocation.png"];
        }else{((bmkpinannotationview*) newannotation). Image = [UIImage imagenamed:@ "Map_mark.png"];
        } UIView *popview = [[UIView alloc]initwithframe:cgrectmake (0, 0, 220, 60)]; PopView.layer.cornerRadius = 3;//Set the rounded popView.layer.borderWidth = 1;//Set the width of the border, of course you can not popview.layer.b
        Ordercolor = [[Uicolor Lightgraycolor] cgcolor];//sets the color of the border popView.layer.masksToBounds = YES;
        Popview.backgroundcolor = [Qqtstringplist colorplistforkey:@ "QQT_BC"];
        
        [Popview setbackgroundcolor:[[qqtstringplist colorplistforkey:@ "QQT_BC"]colorwithalphacomponent:0.5]];
        UILabel *carname = [[UILabel alloc]initwithframe:cgrectmake (0, 0, 220, 60)];
        Carname.text = [annotation subtitle];
        Carname.font = [Uifont systemfontofsize:14];
        Carname.textcolor = [Uicolor blackcolor]; Carname.linebreakmode = ktextlinebreakbycharwrapping;
        Carname.textalignment = Ktextalignmentcenter;
        Carname.numberoflines = 0;
        [Popview Addsubview:carname];
        Bmkactionpaopaoview *pview = [[Bmkactionpaopaoview Alloc]initwithcustomview:popview];
        Pview.frame = CGRectMake (0, 0, 220, 63);
        ((bmkpinannotationview*) newannotation). Paopaoview = nil;
        ((bmkpinannotationview*) newannotation). Paopaoview = PView;
    [Newannotation Setselected:yes];
} return newannotation;
 }



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.