Introduction to "iOS Development 111" Custom pin annotation and 2 navigational dashes

Source: Internet
Author: User

(1) Custom pin annotation style, that is, define the view, the main method is as follows, passing a PIN annotation model, and then return to a Mkannotationview, This mkannotationview has an image property that sets this property so that it can be styled.

-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id<mkannotation>) annotation{}


Key hints, this mkannotationview and Tableviewcell similar, can be recycled, first taken from the Mapview, not to be created again.

Main code:

#import "ViewController.h" #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> #import " WPAnnotation.h "@interface Viewcontroller () <MKMapViewDelegate> @property (weak, nonatomic) Iboutlet Mkmapview * Mapview, @property (nonatomic,strong) Cllocationmanager *locmgr; @end @implementation viewcontroller-(    Cllocationmanager *) locmgr{if (_locmgr==nil) {_locmgr=[[cllocationmanager alloc]init]; } return _locmgr;}    -(void) viewdidload {[Super viewdidload];    if ([[Uidevice currentdevice].systemversion doublevalue]>=8.0) {[Self.locmgr requestwheninuseauthorization];    }//Set proxy self.mapview.delegate=self;    Add two pins wpannotation *anno0=[[wpannotation alloc]init];    Anno0.coordinate=cllocationcoordinate2dmake (40, 116);    [email protected] "full poly de";    [email protected] "The best roast Duck restaurant in Beijing";    [email protected] "category_1";        [Self.mapview Addannotation:anno0];    Wpannotation *anno1=[[wpannotation Alloc]init]; Anno1.coordiNate=cllocationcoordinate2dmake (39, 115);    [email protected] "Wanda Cinema";    [email protected] "The best of all China's top viewing sites";    [email protected] "category_5"; [Self.mapview addannotation:anno1];} -(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id<mkannotation>) annotation{static    NSString *[email protected] "Annoview";    Mkannotationview *annoview=[mapview Dequeuereusableannotationviewwithidentifier:id];        if (annoview==nil) {Annoview=[[mkannotationview alloc]initwithannotation:annotation ReuseIdentifier:ID];    Click on the PIN to appear the message (Custom view pin default Click does not eject) Annoview.canshowcallout=yes;        }//re-pass the annotation model (Assignment) annoview.annotation=annotation;    Wpannotation *anno=annotation;        Annoview.image=[uiimage ImageNamed:anno.icon]; return Annoview;} @end

Pin model, one more icon property, because we want to customize the pin, so we need the graphic properties:

#import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface wpannotation:nsobject< Mkannotation> @property (nonatomic, assign) cllocationcoordinate2d coordinate; @property (nonatomic, copy) NSString * Title: @property (nonatomic, copy) nsstring *subtitle;//custom pin picture @property (nonatomic,copy) nsstring *icon; @end

(2) If we join the tracking user's existing location

Tracking user location self.mapview.usertrackingmode=mkusertrackingmodefollow;

The following error is found:[mkuserlocation icon]: Unrecognized selector sent to instance 0x7f89baecab50

The main reason is that the mkuserlocation that tracks the user's location is also a pin (the blue glow of the circle), it also has to go through viewforannotation This proxy method to return the custom pin, but it does not have the Icon property, So the error. We should add a judgment to the viewforannotation :

If the system comes with a PIN, the default is returned, otherwise the following icon will be set error, because the system pin does not have the Icon property if (![ Annotation Iskindofclass:[wpannotation class]) return nil;


(3) There is also a mkpinannotationview is mkannotationview sub-class, the properties of 2, one is to set the color, that is, you can set the color of the pin, there is a set of pins from the sky.

-(void) viewdidload {[Super viewdidload];    ...... [Self.mapview Addgesturerecognizer:[[uitapgesturerecognizer alloc] initwithtarget:self action: @selector (TapMapView :)]];}    -(void) Tapmapview: (UITapGestureRecognizer *) tap{//Acquisition point Cgpoint Point=[tap LocationInView:tap.view];    Point turn coordinates cllocationcoordinate2d Coordi=[self.mapview convertpoint:point ToCoordinateFromView:self.mapView];    Wpannotation *anno=[[wpannotation Alloc]init];    Anno.coordinate=coordi;    [email protected] "full poly de"; [email protected] "come to a duck, boss!"    "; [Self.mapview Addannotation:anno];} -(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id<mkannotation>) annotation{static    NSString *[email protected] "map";    Mkpinannotationview *annoview= (Mkpinannotationview *) [Mapview Dequeuereusableannotationviewwithidentifier:id];        if (annoview==nil) {Annoview=[[mkpinannotationview alloc]initwithannotation:annotation ReuseIdentifier:ID]; Setting description information can be clicked to appear annoView.canshowcallout=yes;        Set the color annoview.pincolor=mkpinannotationcolorgreen;    Set the first occurrence of falling from the sky Annoview.animatesdrop=yes; } return Annoview;}



(4) Customize a Mkannotationview, and use the Proxy method, monitor the PIN click, click, then pop up a "pin" (only this pin is custom mkannotationview).

We generally return a pin view, using the following method similar to Tableviewcell.

-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id<mkannotation>) annotation{    if ([ Annotation Iskindofclass:[wpdescriptionannotation class]) {        Wpannotationview *annoview=[wpannotationview Annotationwithmapview:mapview];        annoview.annotation=annotation;        return annoview;    } else if ([Annotation iskindofclass:[wpannotation class]]) {        Wptuangouannotationview *annoview=[ Wptuangouannotationview Annotationwithmapview:mapview];        annoview.annotation=annotation;        return annoview;    }    return nil;}

Clicking on a PIN view is also similar to clicking on a line of TableView (here are some useful judgments):

Click on the pin to eject a custom pin as description information-(void) Mapview: (Mkmapview *) Mapview Didselectannotationview: (Mkannotationview *) view{    if (![ View Iskindofclass:[wptuangouannotationview class]]) return;    Remove all re-add, guarantee only 1, and also prevent duplicate for    (id annotation in mapview.annotations) {        if ([annotation iskindofclass:[ Wpdescriptionannotation class]]) {            [Mapview removeannotation:annotation];        }    }    Wpannotation *anno=view.annotation;    Wpdescriptionannotation *descanno=[[wpdescriptionannotation Alloc]init];    Descanno.tuangou=anno.tuangou;    [Mapview Addannotation:descanno];}

We typically add a pin to the project, which has a data model. First assign the data model to a PIN, and then add it. Of course, a pin needs to be set in its own class Settuangou that is to set the data model.

For (Wptuangou *tuan in self.tuangous) {        wpannotation *anno=[[wpannotation alloc]init];        Anno.tuangou=tuan;        [Self.mapview Addannotation:anno];}

In our project, we typically pass models and pins as arguments between different objects.


(5) Navigation Dash


#import "ViewController.h" #import <CoreLocation/CoreLocation.h> #import <MapKit/MapKit.h> #import " WPAnnotation.h "@interface Viewcontroller () <MKMapViewDelegate> @property (weak, nonatomic) Iboutlet Mkmapview * Mapview; @property (Nonatomic,strong) clgeocoder *geocoder; @end @implementation viewcontroller-(Clgeocoder *) Geocoder    {if (_geocoder==nil) {_geocoder=[[clgeocoder alloc]init]; } return _geocoder;}    -(void) viewdidload {[Super viewdidload];        self.mapview.delegate=self;    NSString *[email protected] "Guangzhou";    NSString *[email protected] "Beijing"; This method can only take effect 1, so can not be written separately [Self.geocoder geocodeaddressstring:add1 completionhandler:^ (Nsarray *placemarks, NSError *        Error) {if (error) return;        Clplacemark *frompm=[placemarks Firstobject]; [Self.geocoder geocodeaddressstring:add2 completionhandler:^ (Nsarray *placemarks, NSError *error)            {Clplacemark *topm=[placemarks firstobject]; [Self Addlinefrom:frompM TO:TOPM];    }]; }];} -(void) Addlinefrom: (Clplacemark *) frompm to: (Clplacemark *) topm{//Add 2 pins wpannotation *anno0=[[wpannotation alloc]    INIT];    Anno0.coordinate=frompm.location.coordinate;        [Self.mapview Addannotation:anno0];    Wpannotation *anno1=[[wpannotation Alloc]init];    Anno1.coordinate=topm.location.coordinate;        [Self.mapview Addannotation:anno1];    Set direction request Mkdirectionsrequest *request=[[mkdirectionsrequest Alloc]init];    Set starting point end Mkplacemark *sourcepm=[[mkplacemark ALLOC]INITWITHPLACEMARK:FROMPM];    Request.source=[[mkmapitem ALLOC]INITWITHPLACEMARK:SOURCEPM];    Mkplacemark *destipm=[[mkplacemark ALLOC]INITWITHPLACEMARK:TOPM];    Request.destination=[[mkmapitem ALLOC]INITWITHPLACEMARK:DESTIPM];    Define Direction Object Mkdirections *dirs=[[mkdirections Alloc]initwithrequest:request]; Calculate route [dirs calculatedirectionswithcompletionhandler:^ (Mkdirectionsresponse *response, Nserror *error) {NSLog ( @ "A total of%lu lines", (unsigned long) RESPONSE.ROutes.count);        For (Mkroute *route in response.routes) {[Self.mapview addOverlay:route.polyline]; }    }];} Underline is to add a path, is to add a cover-(Mkoverlayrenderer *) Mapview: (Mkmapview *) Mapview Rendererforoverlay: (id<mkoverlay>)    overlay{mkpolylinerenderer *renderer=[[mkpolylinerenderer Alloc]initwithoverlay:overlay];    Renderer.strokecolor=[uicolor Redcolor]; return renderer;} @end

There is also a way to create a navigation that leverages Mkmapitem:

    Mkmapitem *from=[[mkmapitem Alloc]initwithplacemark:[[mkplacemark alloc] initwithplacemark:frompm];    Mkmapitem *to=[[mkmapitem Alloc]initwithplacemark:[[mkplacemark alloc] initwithplacemark:topm];    Nsmutabledictionary *options=[nsmutabledictionary dictionary];    options[mklaunchoptionsdirectionsmodekey]=mklaunchoptionsdirectionsmodedriving;    Options[mklaunchoptionsshowstraffickey][email protected];    [Mkmapitem Openmapswithitems:@[from,to] launchoptions:options];

Introduction to "iOS Development 111" Custom pin annotation and 2 navigational dashes

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.