import "ViewController.h"
//引入地圖框架 可視化必須引框架
import <MapKit/MapKit.h>
import "MyAnnotation.h"
@interface ViewController ()<MKMapViewDelegate>
//地圖視圖屬性
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
//負(fù)責(zé)定位的類 地圖的使用必須搭配定位
@property(nonatomic,strong)CLLocationManager * locationManager;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
//1.跳過判斷是否能定位的這個(gè)步驟!!!!
//2.請求授權(quán)
self.locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
//請求用戶授權(quán)
[self.locationManager requestWhenInUseAuthorization];
}//3.讓地圖上顯示用戶當(dāng)前的位置
self.mapView.userInteractionEnabled = MKUserTrackingModeFollow;
//4.設(shè)置代理對像
self.mapView.delegate = self;
}
//添加一個(gè)大頭針其實(shí)需要兩個(gè)對象協(xié)作完成,一個(gè)叫做大頭針對象(其實(shí)就是那個(gè)針),另一個(gè)就是大頭針模型對象(就是我們自定義的(moAnnotation))幫我們存儲(chǔ)大頭針?biāo)ǖ奈恢眯畔?br>
//所以 以下方法中 我們不是真的創(chuàng)建那根針 而是創(chuàng)建大頭針模型對象,因?yàn)榇箢^針對象由系統(tǒng)創(chuàng)建,會(huì)根據(jù)大頭針模型存儲(chǔ)的位置信息顯示在地圖上
//點(diǎn)擊輕拍視圖添加大頭針
- (IBAction)tapAction:(UITapGestureRecognizer *)sender {
//獲取輕拍手勢 輕拍的點(diǎn)
CGPoint touchPoint = [sender locationInView:self.mapView];
//把 x y的值轉(zhuǎn)化為經(jīng)緯度 并且讓大頭針模型存儲(chǔ)起來
CLLocationCoordinate2D coordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
//創(chuàng)建大頭針模型
MyAnnotation * annotation = [[MyAnnotation alloc] init];
//給模型賦值
annotation.coordinate = coordinate;
annotation.title = @"主標(biāo)題";
annotation.subtitle = @"副標(biāo)題...";
//添加大頭針標(biāo)注信息
[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>
//注意此模型是特殊的大頭針視圖模型 屬性不準(zhǔn)亂寫 要按照協(xié)議屬性
@property(nonatomic,assign)CLLocationCoordinate2D coordinate;
@property(nonatomic,strong)NSString * title,*subtitle;