MKMapView使用

51 篇文章 0 订阅
#import "ViewController.h"
#import <MapKit/MapKit.h>

@interface ViewController ()<MKMapViewDelegate>
@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<MKAnnotation>)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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值