</pre>当用到mapView的时候,要不就是地图不出来,要不就是定位不显示,要不就是没有弹框提示,着实费了点脑筋,记录一下以后也许用的着。这个Demo有两个作用<p></p><p>(1)定位到用户所在的位置</p><p>(2)自定义地图的显示范围</p><p></p><pre name="code" class="objc">- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
if ([CLLocationManager locationServicesEnabled]) {
//定位初始化(IOS 8以后要正常使用定位功能必须请求定位授权)
[self.mgr requestWhenInUseAuthorization];
//ios 9不能获取位置(不用设置代理获取位置),必须写上以下两句的任意的一句才能调用- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
//详细的定位
self.mapView.userTrackingMode = MKUserTrackingModeFollow;
//大致的定位
//self.mapView.showsUserLocation = YES;
//监控地图的相关行为
self.mapView.delegate = self;
}else{
NSLog(@"检查定位状况");
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
//一打开地图就设置中心点坐标
// [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
// 设置显示的区域范围的大小
MKCoordinateSpan span = MKCoordinateSpanMake(0.983, 0.609);
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[self.mapView setRegion:region animated:YES];
}
//重新回到用户位置(用户体验)
- (IBAction)back:(id)sender {
[self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
}
//显示地图的区域改变了就会调用(位置和范围改变都会调用),越是要放大,区域跨度就越小
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
NSLog(@"%f %f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}
这里需要注意的是
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation这个方法跟前面的<p style="margin-top: 0px; margin-bottom: 0px; font-size: 11px; line-height: normal; font-family: Menlo; color: rgb(76, 191, 87);"><span style="font-variant-ligatures: no-common-ligatures">- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations是不一样的</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 11px; line-height: normal; font-family: Menlo; color: rgb(76, 191, 87);"><span style="font-variant-ligatures: no-common-ligatures"><span style="color: rgb(76, 191, 87); font-family: Menlo; font-size: 11px; white-space: pre; background-color: rgb(240, 240, 240);">第一个返回的是定位到的用户的位置只有一个,而第二个返回的是<span style="color: rgb(76, 191, 87); font-family: Menlo; font-size: 11px; white-space: pre; background-color: rgb(240, 240, 240);">locations数组,是不断变化着的location。</span></span>
</span></p>