import "ViewController.h"
//引入地图框架 可视化必须引框架
import <MapKit/MapKit.h>
import "MyAnnotation.h"
@interface ViewController ()<MKMapViewDelegate>
//地图视图属性
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
//负责定位的类 地图的使用必须搭配定位
@property(nonatomic,strong)CLLocationManager * locationManager;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
//1.跳过判断是否能定位的这个步骤!!!!
//2.请求授权
self.locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
//请求用户授权
[self.locationManager requestWhenInUseAuthorization];
}//3.让地图上显示用户当前的位置
self.mapView.userInteractionEnabled = MKUserTrackingModeFollow;
//4.设置代理对像
self.mapView.delegate = self;
}
//添加一个大头针其实需要两个对象协作完成,一个叫做大头针对象(其实就是那个针),另一个就是大头针模型对象(就是我们自定义的(moAnnotation))帮我们存储大头针所定的位置信息
//所以 以下方法中 我们不是真的创建那根针 而是创建大头针模型对象,因为大头针对象由系统创建,会根据大头针模型存储的位置信息显示在地图上
//点击轻拍视图添加大头针
- (IBAction)tapAction:(UITapGestureRecognizer *)sender {
//获取轻拍手势 轻拍的点
CGPoint touchPoint = [sender locationInView:self.mapView];
//把 x y的值转化为经纬度 并且让大头针模型存储起来
CLLocationCoordinate2D coordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
//创建大头针模型
MyAnnotation * annotation = [[MyAnnotation alloc] init];
//给模型赋值
annotation.coordinate = coordinate;
annotation.title = @"主标题";
annotation.subtitle = @"副标题...";
//添加大头针标注信息
[self.mapView addAnnotation:annotation];
}
pragma mark -- 移除大头针操作
- (IBAction)removeAnnotation:(UIButton *)sender {
[self.mapView removeAnnotations:self.mapView.annotations];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
MyAnnotation.h
import <Foundation/Foundation.h>
import <MapKit/MapKit.h>
@interface MyAnnotation : NSObject<MKAnnotation>
//注意此模型是特殊的大头针视图模型 属性不准乱写 要按照协议属性
@property(nonatomic,assign)CLLocationCoordinate2D coordinate;
@property(nonatomic,strong)NSString * title,*subtitle;
网友评论