地图结合的定位
1. 和单纯定位相同部分
iOS8+都必须征求用户的同意
2. 和单纯定位不同部分
a. 协议:MKMapViewDelegate (MapKit Framework)
b.类/控件:地图控件MKMapView
c. 定位的方式也不同: 通过地图视图的一个属性
细节:
a. 如果手动往storyboard中拖拽一个MKMapView, 需要手动导入MapKit Framework;
b. 如果用纯代码的方式添加MKMapView, a步骤省略
c. CLLocationManager对象声明一个属性,不会造成弹出框很快收回 (!!!!!)
viewController.m
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "TRAnnotation.h"
@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
//CLLocationManager
@property (nonatomic,strong) CLLocationManager *mgr;
//CLGeocoder
@property (nonatomic, strong) CLGeocoder *geocoder;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mgr = [CLLocationManager new];
self.geocoder = [CLGeocoder new];
//征求用户的意见 (Info.plist)
[self.mgr requestWhenInUseAuthorization];
//设置代理
self.mapView.delegate = self;
//设置地图的属性
self.mapView.rotateEnabled = YES;
//设置地图的显示方式(卫星/卫星混合)
self.mapView.mapType = MKMapTypeStandard;
//执行定位操作
self.mapView.userTrackingMode = MKUserTrackingModeFollow;
}
#pragma mark --- MapView Delegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
//使用反地理编码来获取用户位置对应的详细信息(国家/省)
[self.geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *placemarks, NSError *error) {
//使用placemark给定的信息,设置用户位置大头针的文本信息
CLPlacemark *placemark = [placemarks lastObject];
//title
userLocation.title = placemark.name;
//subtitle
userLocation.subtitle = placemark.locality;
}];
//显示地图
MKCoordinateSpan span = MKCoordinateSpanMake(0.5, 0.5);
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[self.mapView setRegion:region animated:YES];
}
//地图拖拽的情况调用方法
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
NSLog(@"span: %f; %f", self.mapView.region.span.latitudeDelta, self.mapView.region.span.longitudeDelta);
}
//自定义大头针必须实现的代理方法
//1.地图上有多少大头针,调用多少次
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
NSLog(@"自定义大头针方法");
//6.如果默认返回nil,当前的用户位置为默认的蓝色;其他的默认是红色的
// return nil;
//把用户位置所属的大头针类型排除在外
if ([annotation isKindOfClass:[MKUserLocat