以下是关于mapView的定位以及显示的中心和区域,以及那个定位到的大头针的显示的信息展示*
1.导入#import
mapView.delegate = self;
// 如果想利用MapKit获取用户的位置, 可以追踪
mapView.userTrackingMode = MKUserTrackingModeFollow;
// 设置不允许地图旋转
mapView.rotateEnabled = NO;
3.实现maoView的代理
MKMapViewDelegate
#pragma mark - MKMapViewDelegate
/**
* 每次更新到用户的位置就会调用(调用不频繁, 只有位置改变才会调用)
*
* @param mapView 促发事件的控件
* @param userLocation 大头针模型
*/
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self.geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *placemark = [placemarks firstObject];
NSLog(@"获取地理位置成功 name = %@ locality = %@", placemark.name, placemark.locality);
//这里可以设置定位到的那个大头针的标题和子标题
userLocation.title = placemark.name;
userLocation.subtitle = placemark.locality;
}];
CLLocationCoordinate2D center = userLocation.location.coordinate;
MKCoordinateSpan span = MKCoordinateSpanMake(5, 5);
MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
//设置mapView当前显示的区域
[self.mapView setRegion:region animated:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 创建大头针模型
CJAnnotation *annotation = [[CJAnnotation alloc] init];
annotation.title = @"衢州市";
annotation.subtitle = @"沙埠村";
CGFloat latitude = 36.821199 + arc4random_uniform(20);
CGFloat longitude = 116.858776 + arc4random_uniform(20);
annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
[self.mapView addAnnotation:annotation];
}
以下是随机产生大头针
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 创建大头针模型
CJAnnotation *annotation = [[CJAnnotation alloc] init];
annotation.title = @"衢州市";
annotation.subtitle = @"沙埠村";
CGFloat latitude = 36.821199 + arc4random_uniform(20);
CGFloat longitude = 116.858776 + arc4random_uniform(20);
annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
[self.mapView addAnnotation:annotation];
}
这里的CJAnnotation是一个自定义的大头针模型,这个模型是集成NSObject的,但是必须实现MKAnnotation协议,因为这个[self.mapView addAnnotation:annotation];要求添加的annotation就是必须要实现这个协议的