ios自带的MKMapView学习

当与地图关联一般是需要获取用户的当前位置的。MKMapView这个类是在MapKit.framework.这个框架中的。但是获取用户的经纬度又是另外一个类CLLocationManager这个类在CoreLocation.framework中的。

使用CLLocationManager我们需要设置  CLLocationManagerDelegate 代理。

locationManager= [[CLLocationManager alloc]init];

locationManager.delegate=self;

locationManager.distanceFilter=kCLLocationAccuracyNearestTenMeters;//指定的最小距离米更新。这个是10米

locationManager.desiredAccuracy=kCLLocationAccuracyBest;所需的定位精度 

if([[[UIDevice currentDevice]systemVersion]floatValue] >=8) {

[locationManagerrequestWhenInUseAuthorization];// 

}

[locationManagerstartUpdatingLocation];//开始更新

使用CLLocationManager我们需要在info.plist文件里面配置NSLocationWhenInUseDescription 或者NSLocationAlwaysUsageDescription他们都是字符串类型。就是当要用到CLLocationManager要向用户请求是否允许程序访问用的位置。上面二个就是描述提示的文字。

- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation ;在这个方法里面我们就可以访问到用户的当前位置的经纬度。

MKMapView继承的是UIView,只是显示的时候是地图的画面。我们需要把当前用户的位置显示在地图上面

_mapview=[[MKMapView alloc]initWithFrame:CGRectMake(0,64,SCREEN_WIDTH,SCREEN_HEIGHT-64)];

_mapview.delegate=self;    //MKMapViewDelegate                 

_mapview.userInteractionEnabled=YES;

MKMapView 这样设置之后并不能显示用户的当前位置。

需要实现代理方法

- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id)annotation {

MKAnnotationView*annotationView =nil;

if(![annotationisKindOfClass:[MKUserLocation class]])

{

MKAnnotationView*annotationView =[_mapviewdequeueReusableAnnotationViewWithIdentifier:@"CustomAnnotation1"];

if(!annotationView) {

annotationView = [[MKAnnotationViewalloc]initWithAnnotation:annotation

reuseIdentifier:@"CustomAnnotation1"] ;

annotationView.canShowCallout=NO;

annotationView.image= [UIImageimageNamed:@"mypositionimage"];

}  //这一部分先忽略,下一篇写自定义标注图标

}

returnannotationView;

}

这样用户的当前位置如下显示蓝色的渐变。

ios自带的MKMapView学习_第1张图片

你可能感兴趣的:(ios自带的MKMapView学习)