iOS 获取地图视图中心点经纬度&长按添加大头针

 

// 在info.plist 添加配置 上线对应的值要写说明

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ViewController ()
<
CLLocationManagerDelegate,
MKMapViewDelegate
>

@property(nonatomic,strong)MKMapView *mapView;
/// 定位管理器
@property(nonatomic,strong)CLLocationManager *locationManager;
/// 放大缩小用
@property (nonatomic) MKCoordinateRegion region;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.mapView];
    [self.locationManager startUpdatingLocation];
}

#pragma mark ————————— 地图位置更新 —————————————
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center = centerCoordinate;
    _region = region;
    
    NSLog(@" 经纬度 %f,%f",centerCoordinate.latitude, centerCoordinate.longitude);
    
    CLLocation *location = [[CLLocation alloc]initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
    
    [self cityNameFromLoaction:location block:^(CLPlacemark *place, NSString *city) {
        
    }];
 
}

#pragma mark-CLLocationManagerDelegate
/**
*  更新到位置之后调用
*
*  @param manager   位置管理者
*  @param locations 位置数组
*/
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:( NSArray *)locations
{
    NSLog(@"定位到了");
    //停止位置更新
    [manager stopUpdatingLocation];
    
    CLLocation *location = [locations firstObject];
    //位置更新后的经纬度
    CLLocationCoordinate2D theCoordinate =  location.coordinate;

    //设置地图显示的中心及范围
    MKCoordinateRegion theRegion;
    theRegion.center = theCoordinate;
    
    // 坐标跨度
    MKCoordinateSpan theSpan;
    theSpan.latitudeDelta = 0.01;
    theSpan.longitudeDelta = 0.01;
    theRegion.span = theSpan;
    [self.mapView setRegion:theRegion];
    
    [self cityNameFromLoaction:location block:^(CLPlacemark *place, NSString *city) {
        NSLog(@"位置:%@", place.name);
    }];
}

#pragma mark ————————— 地理位置返编码 —————————————
-(void)cityNameFromLoaction:(CLLocation *)location block:(void(^)(CLPlacemark *place ,NSString *city))block
{
    __weak typeof(self) weakSelf = self;
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error)
        {
            for (CLPlacemark *place in placemarks)
            {
                NSDictionary *location = [place addressDictionary];
//                NSLog(@"位置:%@", place.name);
//                NSLog(@"国家:%@", place.country);
//                NSLog(@"城市:%@", place.locality);
//                NSLog(@"区:%@", place.subLocality);
//                NSLog(@"街道:%@", place.thoroughfare);
//                NSLog(@"子街道:%@", place.subThoroughfare);
                // 将获得的所有信息显示到label上
                // 获取城市
                NSString *city = place.name;
                // 设置地图显示的类型及根据范围进行显示  安放大头针
                [weakSelf addPointFromCoordinate:place.location.coordinate title:city];
                block(place ,place.name);
            }
        }
        else
        {
            NSLog(@"%@",error);
        }
    }];
}

#pragma mark ————————— 长按添加大头针事件 —————————————
- ( void )lpgrClick:( UILongPressGestureRecognizer *)lpgr
{
     // 判断只在长按的起始点下落大头针
     if (lpgr.state == UIGestureRecognizerStateBegan )
     {
         // 首先获取点
         CGPoint point = [lpgr locationInView:self.mapView];
         // 将一个点转化为经纬度坐标
         CLLocationCoordinate2D center = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
         [self addPointFromCoordinate:center title:@"位置"];
     }
}


#pragma mark ————————— 添加大头针 —————————————
-(void)addPointFromCoordinate:(CLLocationCoordinate2D)coordinate
                        title:(NSString *)title
{
    NSLog(@"当前城市:%@" ,title);
    self.title = title;
    MKPointAnnotation *pinAnnotation = [[MKPointAnnotation alloc] init];
    pinAnnotation.coordinate = coordinate;
    pinAnnotation.title = title;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotation:pinAnnotation];
}

/**
 *  授权状态发生改变时调用
 *
 *  @param manager 位置管理者
 *  @param status  状态
 */
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
            // 用户还未决定
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定");
            break;
        }
            // 问受限
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
            // 定位关闭时和对此APP授权为never时调用
        case kCLAuthorizationStatusDenied:
        {
            // 定位是否可用(是否支持定位或者定位是否开启)
            if([CLLocationManager locationServicesEnabled])
            {
                NSLog(@"定位开启,但被拒");
            }
            else
            {
                NSLog(@"定位关闭,不可用");
            }
            break;
        }
            // 获取前后台定位授权
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            //  case kCLAuthorizationStatusAuthorized: // 失效,不建议使用
            NSLog(@"获取前后台定位授权");
            break;
        }
            // 获得前台定位授权
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"获得前台定位授权");
            break;
        }
        default:
            break;
    }
}

//获取当前位置
-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        CLLocationManager * locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self ;
        //kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        locationManager.distanceFilter = 50.0f;
        if (([[[ UIDevice currentDevice] systemVersion] doubleValue] >= 8.0))
        {
            [locationManager requestAlwaysAuthorization];
        }
       _locationManager = locationManager;
    }
    return _locationManager;
}

-(MKMapView *)mapView{
    if (!_mapView) {
        MKMapView *mapView = [[MKMapView alloc]init];
        // 接受代理
        mapView.delegate = self;
        mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
        mapView.zoomEnabled = YES ;
        mapView.showsUserLocation = YES ;
        mapView.scrollEnabled = YES ;
        mapView.delegate = self ;
         // 长按手势  长按添加大头针
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]initWithTarget: self action: @selector (lpgrClick:)];
        [mapView addGestureRecognizer:lpgr];
        _mapView = mapView;
    }
    return _mapView;
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值