iOS中MKMapView的使用

#import "ViewController.h"
#import 

@interface ViewController ()
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) CLLocationManager *mgr;
@end

@implementation ViewController
- (IBAction)addAnnotations:(id)sender {
    MKPointAnnotation *annotation = [MKPointAnnotation new];
    CLLocationDegrees latitude = 35.4332 + arc4random_uniform(10);
    CLLocationDegrees longitude = 119.3342 + arc4random_uniform(10);
    [annotation setCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];
    annotation.title = @"China";
    annotation.subtitle = @"City";
    [self.mapView addAnnotation:annotation];
    MKCoordinateSpan span = MKCoordinateSpanMake(21, 22);
    MKCoordinateRegion region = MKCoordinateRegionMake(annotation.coordinate, span);
    [self.mapView setRegion:region];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
    NSLog(@"%s",__func__);
    static NSString *identifier = @"annotation";
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if(!annotation) {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        annotationView.canShowCallout = YES;
        annotationView.pinTintColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.4 alpha:1.0];
        annotationView.leftCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeCustom];
    } else {
        annotationView.annotation = annotation;
    }
    return annotationView;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    //1.初始化manager对象
    self.mgr = [CLLocationManager new];
    //2.征求用户的同意/授权(>=iOS8.0+假设用户同意)+Info.plist添加key
    [self.mgr requestWhenInUseAuthorization];
    //3.设置mapView属性(和定位相关属性)
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    //4.设置mapView的代理
    self.mapView.delegate = self;
    self.mapView.rotateEnabled = NO;
    self.mapView.mapType = MKMapTypeStandard;
}

//监听用户的位置
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    //打印用户的位置
    NSLog(@"纬度%f; 经度%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    userLocation.title = @"userLocation";
    userLocation.subtitle = @"detailLocation";
}
//监听用户挪动地图停止的时机
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    //region:设备上显示的那部分称为地图视图的区域
    NSLog(@"用户挪动地图视图停止...");
}

@end

你可能感兴趣的:(iOS中MKMapView的使用)