IOS Study Notes 20-map (2) MapKit framework

Source: Internet
Author: User

IOS Study Notes 20-map (2) MapKit framework
1. Introduction to map development

Since iOS6.0, map data is no longer driven by Google, but switched to its own map. Of course, its data in China isAMAPProvided.

There are three main ways to develop maps in iOS: MapKitThe framework is used for map development. This method can be used to precisely control maps and call the map application provided by Apple. It is mainly used for some simple map applications and cannot be precisely controlled using the third-party map Development SDK library.

The most frequently usedMapKitSo this section only talks aboutMapKit.

Ii. MapKit core class

MapKitIs A Map Display Control.MKMapViewThe following are common attributes, object methods, and proxy methods.

1. attributes:
/* User location tracking */@ property (nonatomic) BOOL showsUserLocation;/* <whether to mark the user location on the map */@ property (nonatomic, readonly) MKUserLocation * userLocation; /* <user location */@ property (nonatomic) MKUserTrackingMode userTrackingMode;/* <user trail type */typedef NS_ENUM (NSInteger, MKUserTrackingMode) {MKUserTrackingModeNone = 0, /* <do not track */MKUserTrackingModeFollow,/* <trace */MKUserTrackingModeFollowWithHeading,/* <navigation trace */};/* Set map configuration items */@ property (nonatomic) MKMapType mapType;/* <map type */@ property (nonatomic, readonly) NSArray * annotations;/* <PIN array */typedef NS_ENUM (NSUInteger, MKMapType) {MKMapTypeStandard = 0, /* <Standard Map */MKMapTypeSatellite,/* <satellite map */MKMapTypeHybrid,/* 

The pin is the annotation displayed on the map:

2. Object method:
/* Add a pin */-(void) addAnnotation :( id
  
   
) Annotation;-(void) addAnnotations :( NSArray
   
    
> *) Annotations;/* delete a pin */-(void) removeAnnotation :( id
    
     
) Annotation;-(void) removeAnnotations :( NSArray
     
      
> *) Annotations;/* select a pin and deselect a pin */-(void) selectAnnotation :( id
      
        ) Annotation animated :( BOOL) animated;-(void) deselectAnnotation :( id
       
         ) Annotation animated :( BOOL) animated;/* Get The Pin view */-(MKAnnotationView *) viewForAnnotation :( id
        
          ) Annotation;/* obtain the pin view control from the buffer pool */-(MKAnnotationView *) dequeueReusableAnnotationViewWithIdentifier :( NSString *) identifier; /* set the display area and map center coordinates */-(void) setRegion :( MKCoordinateRegion) region animated :( BOOL) animated;-(void) setCenterCoordinate :( handler) coordinate animated :( BOOL) animated;/* convert longitude and latitude coordinates to UIKit coordinates, and convert UIKit coordinates to latitude and longitude coordinates */-(CGPoint) convertCoordinate :( CLLocationCoordinate2D) coordinate toPointToView :( UIView *) view;-(PreView) convertPoint :( CGPoint) point toCoordinateFromView :( UIView *) view;
        
       
      
     
    
   
  
3. Common proxy Methods MKMapViewDelegate:
/* When the map is loaded, it will call */-(void) mapViewDidFinishLoadingMap :( MKMapView *) mapView;/* If the map fails to be loaded, it will call */-(void) mapViewDidFailLoadingMap :( MKMapView *) mapView withError :( NSError *) error;/* when the user location changes, the system calls */-(void) mapView :( MKMapView *) mapView didUpdateUserLocation :( MKUserLocation *) userLocation; /* When the display area changes, the system calls */-(void) mapView :( MKMapView *) mapView regionDidChangeAnimated :( BOOL) animated;/* When you click the selected pin, the system calls */-(void) mapView :( MKMapView *) mapView didSelectAnnotationView :( MKAnnotationView *) view;/* call */-(void) mapView :( MKMapView *) mapView preview :( MKAnnotationView *) view when the PIN is deselected; /* display the pin on the map. The function is similar to the tableView of UITableView: cellForRowAtIndexPath: Method */-(MKAnnotationView *) mapView :( MKMapView *) mapView viewForAnnotation :( id
         
          
) Annotation;
         
3. Use MapKit 1. First add the header file:
#import 
          
2. initialize the Map Display Control MKMapView
-(Void) initMapView {CGFloat x = 0; CGFloat y = 20; CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height; // create MKMapView and set the control View Size MKMapView * mapView = [[MKMapView alloc] initWithFrame: CGRectMake (x, y, width, height)]; // set the map type mapView. mapType = MKMapTypeStandard; // sets the proxy mapView. delegate = self; [self. view addSubview: mapView]; self. mapView = mapView ;}
3. Before the user location tracking function is enabled, you only need to set the User tracking mode in mapView:DidUpdateUserLocation:In the proxy method, after setting the map center and display range in iOS8, the usage is slightly different: you must follow the instructions in the previous positioning chapter to obtain the positioning service authorization for the front-end or front-end. The following is the link:
IOS study note 19-map (1) Positioning CoreLocation you do not need to specify the center point. By default, the current position is set to the center point and the automatically displayed area range is only after the current position is located mapView:DidUpdateUserLocation:The proxy method is called.
-(Void) viewDidLoad {[super viewDidLoad]; // obtain the permission of the positioning service [self requestUserLocationAuthor]; // initialize MKMapView [self initMapView];}-(void) requestUserLocationAuthor {// if no authorization is obtained, obtain the authorization request self. locationM = [[CLLocationManager alloc] init]; if ([CLLocationManager locationServicesEnabled]) {if ([CLLocationManager authorizationStatus]! = Kclthorizationstatusauthorizedwheninuse) {[self. locationM requestWhenInUseAuthorization] ;}}- (void) initMapView {CGFloat x = 0; CGFloat y = 20; CGFloat width = self. view. frame. size. width; CGFloat height = self. view. frame. size. height; // create the MKMapView object MKMapView * mapView = [[MKMapView alloc] initWithFrame: CGRectMake (x, y, width, height)]; // set the map type mapView. mapType = MKMapTypeStandard; // sets the User tracking mode mapView. userTrackingMode = MKUserTrackingModeFollow; mapView. delegate = self; [self. view addSubview: mapView]; self. mapView = mapView;} # pragma mark-MKMapViewDelegate/* call */-(void) mapView :( MKMapView *) mapView didUpdateUserLocation: (MKUserLocation *) userLocation {CLLocation * location = userLocation. location; CLLocationCoordinate2D coordinate = location. coordinate; NSLog (@ "longitude: % f, latitude: % f", coordinate. latitude, coordinate. longpolling );}

4. Add a pin

MapKit does not have its own PIN, only the pin ProtocolMKAnnotation, We need to customize the pin:
1. Create an inheritanceNSObjectClass
2. ImplementationMKAnnotationProtocol
3. You must create an attribute to store the pin position.

@property (nonatomic) CLLocationCoordinate2D coordinate;
The LTAnnotation class that I created is as follows:
# Import
           
            
# Import
            
             
@ Interface LTAnnotation: NSObject
             
              
/* Required properties */@ property (nonatomic) CLLocationCoordinate2D coordinate;/* optional properties */@ property (nonatomic, copy) NSString * title; @ property (nonatomic, copy) NSString * subtitle;/* Custom Attributes */@ property (nonatomic, strong) UIImage * icon; @ end @ implementation LTAnnotation @ end
             
            
           
The following is the actual usage:
-(Void) viewDidLoad {[super viewDidLoad]; // request positioning authorization [self requestUserLocationAuthor]; // initialize MKMapView [self initMapView]; // Add a pin [self addAnnotationsToMapView];} -(void) addAnnotationsToMapView {CLLocationCoordinate2D location1 = locate (22.54, 114.02); // create a pin LTAnnotation * annotation = [[LTAnnotation alloc] init]; annotation. title = @ "persistent"; annotation. subtitle = @ "the store opened by persistent brother"; annotation. coordinate = location1; annotation. icon = [UIImage imageNamed: @ "red"]; // Add a pin [self. mapView addAnnotation: annotation1];}

5. Custom pin View

Is the above pin ugly?MKMapViewDefault style pin ViewMKAnnotationViewFirst, let's take a look at its common attributes:

@ Property (nonatomic, strong) id
              
               
Annotation;/* <pin data */@ property (nonatomic, strong) UIImage * image;/* <pin icon */@ property (nonatomic, readonly) NSString * reuseIdentifier; /* <unique ID of the pin */@ property (nonatomic) CGPoint calloutOffset;/* <offset of the pop-up view */@ property (nonatomic) BOOL selected; /* <whether to select */@ property (nonatomic) BOOL canShowCallout;/* <whether to click the pop-up view */@ property (nonatomic, strong) UIView * leftCalloutAccessoryView; /* <display the view on the left */@ property (nonatomic, strong) UIView * rightCalloutAccessoryView;/* <display the view on the right */
              
Set MKAnnotationViewTo customize the pin View:
/* This method is called whenever the PIN is displayed on the visual interface. The blue point of the user's position is also a pin, and */-(MKAnnotationView *) is also called *) mapView :( MKMapView *) mapView viewForAnnotation :( id
               
                
) Annotation {if ([annotation isKindOfClass: [LTAnnotation class]) {LTAnnotation * annotationLT = (LTAnnotation *) annotation; // similar to the reuse mechanism of UITableViewCell, the pin view also has a reuse mechanism static NSString * key = @ "AnnotationIdentifier"; MKAnnotationView * view = [self. mapView dequeueReusableAnnotationViewWithIdentifier: key]; if (! View) {view = [[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: key];} // set the view of Pin data. annotation = annotation; // The default value of the custom pin is NO, indicating that the view cannot be displayed. Here, you can click the view to display the view. canShowCallout = YES; // you can specify the pin icon view. image = annotationLT. icon; // set UIImage * leftImage = [UIImage imageNamed: @ "cafeIcon"]; UIImageView * leftView = [[UIImageView alloc] initWithImage: leftImage]; leftView. bounds = CGRectMake (0, 0, 50, 50); view. outputs = leftView; // set UIImage * rightImage = [UIImage imageNamed: @ "cafeRight"]; UIImageView * rightView = [[UIImageView alloc] initWithImage: rightImage]; rightView. bounds = CGRectMake (0, 0, 50, 50); view. rightCalloutAccessoryView = rightView; return view;} // return nil, indicating that the default Style return nil is displayed ;}
               

Iv. Extended-custom pin pop-up Details View

If you pay attention to some map applications, you will find that their pop-up views are completely different from ours. How is that implemented?

In fact, it's not a pop-up view. It's a pin, but it's just like a pop-up view.

Implementation idea: When you click a regular pin, remove the other details pins on the map and add the details pins of the current pin. When the general pin is deselected, remove all the details pins on the map mapView:viewForAnnotation:In the method, set the general pin view and details pin view. Below is some of the Code to be implemented. [The effect is relatively casual. Sorry ]:
# Pragma mark-map control proxy method/* called when displaying a pin. Note that the annotation parameter in the method is the forthcoming pin object */-(MKAnnotationView *) mapView :( MKMapView *) mapView viewForAnnotation :( id
                
                 
) Annotation {// because the current position annotation is also a pin, you need to determine at this time. This proxy method returns nil using the default pin view if ([annotation isKindOfClass: [LTAnnotation class]) {static NSString * key1 = @ "AnnotationKey1"; MKAnnotationView * annotationView = [_ mapView dequeueReusableAnnotationViewWithIdentifier: key1]; // if the cache pool does not exist, a new if (! AnnotationView) {annotationView = [[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: key1]; annotationView. canShowCallout = NO; // The view cannot be displayed, but the view can be selected} // You can reset the pin model of this type of Pin view (because it may be obtained from the cache pool, location is the location when it is placed in the cache pool) annotationView. annotation = annotation; annotationView. image = (LTAnnotation *) annotation ). icon; // set the image return annotationView In the pin view;} else if ([annotation isKindOfClass: [LTCalloutAnnot Ation class]) {static NSString * key2 = @ "AnnotationCallOutKey2"; MKAnnotationView * calloutView = [_ mapView comment: key2]; // if the cache pool does not exist, create if (! CalloutView) {calloutView = [[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: key2]; calloutView. canShowCallout = NO; // views cannot be displayed, but can be selected} // NO interaction function is provided for the custom pin view that is used as the Details View, you can add other views as needed. annotation = annotation; // you can specify the offset of the detail pin, calloutView. centerOffset = CGPointMake (-50,-80); [self calloutAddSubView: calloutView]; return calloutView;} else {return nil ;}}
                

The above LTCalloutAnnotation and LTAnnotation are actually different class names and attributes.

# Add the subcontrol of the pop-up view to The pragma mark. Here I am very casual. You can have a good idea-(void) calloutAddSubView :( MKAnnotationView *) calloutView {// Add background UIView * background = [[UIView alloc] initWithFrame: CGRectMake (0, 0,100, 60)]; background. backgroundColor = [UIColor whiteColor]; background. layer. borderWidth = 5; background. layer. borderColor = [UIColor blueColor]. CGColor; [calloutView addSubview: background]; // Add image UIImage * image = [UIImage imageNamed: @ "cafeRight"]; UIImageView * imageView = [[UIImageView alloc] initWithImage: image]; imageView. frame = CGRectMake (5, 5, 50, 50); [calloutView addSubview: imageView]; // Add a red block UIView * subview = [[UIView alloc] initWithFrame: CGRectMake (60, 5, 35, 40)]; subview. backgroundColor = [UIColor redColor]; [calloutView addSubview: subview];} # Trigger when pragma mark selects a pin // Add a pin when you click a general pin KCAnnotation as the pop-up Details View of the pin-(void) mapView :( MKMapView *) mapView didSelectAnnotationView :( MKAnnotationView *) view {if ([view. annotation isKindOfClass: [LTAnnotation class]) {LTAnnotation * annotation = view. annotation; // remove other details view when you click a pin [self removeCalloutAnnotation]; // Add details dashboard LTCalloutAnnotation * callout = [[LTCalloutAnnotation alloc] init]; callout. icon = annotation. icon; callout. title = annotation. title; callout. subtitle = annotation. subtitle; callout. coordinate = annotation. coordinate; [self. mapView addAnnotation: callout] ;}# triggered when pragma mark is deselected-(void) mapView :( MKMapView *) mapView didDeselectAnnotationView :( MKAnnotationView *) view {[self removeCalloutAnnotation];} # pragma mark removal details pin-(void) removeCalloutAnnotation {[self. mapView. annotations enumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop) {if ([obj isKindOfClass: [LTCalloutAnnotation class]) {[_ mapView removeAnnotation: obj] ;}}] ;}

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.