103 MapKit基础

0.在xib或者SB中使用mapView要先导入MapKit框架(不是头文件而是框架),否则会crash

1.地图用于显示,要显示当前位置的大头针所以要获得地理位置信息:

 _mgr = [[CLLocationManager alloc]init];
[_mgr requestAlwaysAuthorization];
[_mgr startUpdatingLocation];

2.地图显示出来不会默认显示当前的位置,所以要设置地图到当前位置:

_mapView.userTrackingMode = MKUserTrackingModeFollow;

3.成为mapView的delete会拿到(MKUserLocation *)userLocation

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
}

3.1使用(MKUserLocation *)userLocation的location进行地理反编码

[_geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *mark = [placemarks firstObject];
        userLocation.title = mark.name;
        userLocation.subtitle = mark.locality;
    }];

3.2iOS8在打开地图的时候会默认到当前位置,但是iOS7不会,使用以下方法使其来到当前位置:

    //这个方法会到以userLocation.location为中心的位置(经纬度)
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    //以下方法会去到指定位置,指定中心点(经纬度)和跨度,其中跨度也是和经纬的单位相同,指定显示范围的大小
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion regin = MKCoordinateRegionMake(userLocation.location.coordinate, span);
    [_mapView setRegion:regin animated:YES];

4.最基本的大头针操作,自定义一个model类,并遵守协议(不用实现),声明以下属性:

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
erty (nonatomic, copy) NSString *subtitle;

5.添加大头针的方法:

    Annotation *anno = [[Annotation alloc] init];
    anno.title = @"哈哈哈";
    anno.subtitle = @"哈哈哈";
    CGFloat latitude = 36.821199;
    CGFloat longitude = 116.858776;
    anno.coordinate = CLLocationCoordinate2DMake(latitude , longitude);

    // 添加大头针
    [self.mapView addAnnotation:anno];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章