IOS网络笔记--地图内容4(定位到当前位置)

来源:互联网 发布:淘宝店铺的层级和名次 编辑:程序博客网 时间:2024/06/04 19:44

申明:此为本人学习笔记,若有纰漏错误之处的可留言共同探讨

/*

    思路

 首先显示当前用户的位置,启动定位服务,设置更新 开启定位服务,用完关闭定位服务

 

 步骤

 1 导入库 导入头文件

 2 创建全局MKMapView 初始化

 3 显示用户当前位置 showsUserLocation

 4 启动定位服务  CLLocationManager

 5 设置更新频率 

 6 设置代理 CLLocationManagerDelegate

 7 开启定位服务 startUpdatingLocation

 8 代理方法  ( 定位结束,停止定位)


 */


代码如下:

#import "ViewController.h"

#define SCREEN_WIDTH self.view.frame.size.width

#define SCREEN_HEIGHT self.view.frame.size.height

@interface ViewController ()


@end



@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    // map

    mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 20,SCREEN_WIDTH, SCREEN_WIDTH)];

    [self.view addSubview:mapView];

    

    // 显示用户当前位置

    mapView.showsUserLocation = YES;

    

    // 启动定位服务

    _manager = [[CLLocationManager alloc]init];

    /* 设置更新频率 */

    // 精确度

    _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

    // 频率

    _manager.distanceFilter = 1000.0f;

    _manager.delegate = self;

    [_manager startUpdatingLocation];

    

    

}


#pragma mark - CLLocationManagerDelegate 

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{

    NSLog(@"%@",locations);

    // 定位到的当前位置

    CLLocation *currentLocation = [locations lastObject];

    

    CLLocationCoordinate2D currentCoordinate = currentLocation.coordinate;

    MKCoordinateSpan span = mapView.region.span; // 偏移量

    MKCoordinateRegion region = { currentCoordinate,span}; // 结构体 显示的范围

    

    [mapView setRegion:region animated:YES];

    

    // 结束定位

    [manager stopUpdatingLocation];

    

}



1 0
原创粉丝点击