iOS 原生地图定位,视图中心加大头针,地理位置返编码

info.plist  按需配置
模拟器 地理位置在国外的地理位置返编码没有办法获取

Privacy - Location Always and When In Use Usage Description
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description

.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

typedef void(^BackBlock)(double lat,double lot,NSString *city);

@interface MapVC : UIViewController

@property(nonatomic,copy)BackBlock backBlock;

@end

NS_ASSUME_NONNULL_END

.m

#import "MapVC.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface MapVC ()
<
CLLocationManagerDelegate,
MKMapViewDelegate
>
@property(nonatomic,strong)MKMapView *mapView;
/// 定位管理器
@property(nonatomic,strong)CLLocationManager *locationManager;
/// 移动后的位置标记
@property(nonatomic,strong)CLPlacemark *place;

/ 放大缩小用
//@property (nonatomic) MKCoordinateRegion region;
@end

@implementation MapVC

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

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.backBlock)
    {
        self.backBlock(self.place.location.coordinate.latitude, self.place.location.coordinate.longitude,self.place.name);
    }
}


#pragma mark ————————— 地图位置更新 —————————————
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center = centerCoordinate;
    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)
            {
                weakSelf.place = place;
                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;
}


#pragma mark ————————— 放大事件 —————————————
- (void)addAct
{
//    CLLocationCoordinate2D centCoor = _region.center;
//    MKCoordinateSpan span = _region.span;
//    span.latitudeDelta *= 2;
//    span.longitudeDelta *= 2;
//    MKCoordinateRegion region = MKCoordinateRegionMake(centCoor, span);
//    [self.mapView setRegion:region];
}


#pragma mark ————————— 缩小事件—————————————
- (void)minAct
{
//    CLLocationCoordinate2D centCoor = _region.center;
//    MKCoordinateSpan span = _region.span;
//    span.latitudeDelta *= 0.5;
//    span.longitudeDelta *= 0.5;
//    MKCoordinateRegion region = MKCoordinateRegionMake(centCoor, span);
//    [self.mapView setRegion:region];
}

-(void)dealloc{
    NSLog(@"");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

调用

#import "MapVC.h"

    MapVC *vc = [[MapVC alloc]init];
    __weak typeof(self) weakSelf = self;
    vc.backBlock = ^(double lat, double lot, NSString * _Nonnull city) {
        
        DLog(@"%.15f = %.15f",lat,lot);
        weakSelf.lot = lot;
        weakSelf.lat = lat;
        weakSelf.title = city;
    };
    [self.navigationController pushViewController:vc animated:YES];

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值