最近做了一个小例子 做点笔记 供刚入职场的菜鸟学习,也供自己记忆。
目标:在地图上加上标记 同时复习一下手势的使用
效果图:
具体代码
导入框架:MapKit.framework
创建一个新类 继承NSObject 叫做MyAnnotation 并在后边加上<MKAnnotation>
#import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface MyAnnotation : NSObject<MKAnnotation> @property (nonatomic, assign) CLLocationCoordinate2D coordinate; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *subtitle; @end
viemController.m的代码
#import "ViewController.h" #import <MapKit/MapKit.h> #import "MyAnnotation.h" @interface ViewController ()<MKMapViewDelegate> @property(nonatomic,strong)MKMapView *mapView;//添加一个MApView @property(nonatomic,strong)MKAnnotationView *annotationView;//添加一个标记view @end
//对mapView 的响应的设置并将它加到跟视图中
//添加一个标记
//创建手势实现长按能够加一个标记
- (void)viewDidLoad { [super viewDidLoad]; //对mapView 的响应的设置并将它加到跟视图中 _mapView = [[MKMapView alloc]initWithFrame:self.view.frame]; _mapView.mapType = MKMapTypeStandard; _mapView.delegate = self; [self.view addSubview:_mapView]; //对annotation 的设置 _annotationView = [[MKAnnotationView alloc]initWithFrame:self.view.frame]; //添加一个标记 //设置标记 MyAnnotation *annotation = [[MyAnnotation alloc]init]; //设置经纬度 annotation.title = @"中国"; annotation.subtitle = @"河北"; annotation.coordinate =CLLocationCoordinate2DMake(40, 110); [self.mapView addAnnotation:annotation]; //设置显示标识的内容 [_mapView setCenterCoordinate:annotation.coordinate animated:YES]; //创建手势实现长按能够加一个标记 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)]; [self.view addGestureRecognizer:longPress]; }
//手势长按的实现
-(void)longPress:(UILongPressGestureRecognizer *)sender { //获得点击点的坐标 CGPoint point = [sender locationInView:self.view]; //将点击的地图上点转换成经纬点 CLLocationCoordinate2D Mycoordinate= [self.mapView convertPoint:point toCoordinateFromView:self.mapView]; MyAnnotation *annotation = [[MyAnnotation alloc]init]; annotation.coordinate = Mycoordinate; annotation.title = @"河北"; annotation.subtitle = @"石家庄"; [self.mapView addAnnotation:annotation]; }
#pragma mark-mapView的代理方法-显示标识的方法
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { //创建一个标识的ID static NSString *annotationID = @"annotation"; //先从用户的缓存里找大头针视图 MKPinAnnotationView *view = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationID]; //如果没有大头针视图,自己进行创建 if(!view) { view = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:annotationID]; } //对大头针视图的属性进行设置 //设置标记为传进来的标记 显示气泡 大头针的颜色 view.annotation = annotation; view.canShowCallout = YES; view.pinColor = MKPinAnnotationColorRed; //左边的副视图 view.leftCalloutAccessoryView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"0.png"]]; return view; }