iOS 高德地圖 單次定位

定位知識:
//地圖
@property (nonatomic, strong) MAMapView *mapView;
//位置管理器
@property (nonatomic, strong) AMapLocationManager *locationManager;
//視圖控制器要遵循的協議
@interface SingleLocationViewController () <MAMapViewDelegate, AMapLocationManagerDelegate>

/*
 對定位管理器的配置
 1.初始化
 2.委託
 3.精度

 對視圖控制器的要求
 1.AMapLocationManagerDelegate

 對appDelegate的要求
 #import <AMapFoundationKit/AMapFoundationKit.h>

 -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {

 [AMapServices sharedServices].apiKey = @"9f56b924d3ec22433ef3a451effa33da";
 return YES;

 }


 對Info.plist
 <dict>
    <key>LSApplicationQueriesSchemes</key>
    <array>
 <string>iosamap</string>
    </array>
    <key>NSAppTransportSecurity</key>
    <dict>
 <key>NSAllowsArbitraryLoads</key>
 <true/>
    </dict>


 */
//定位管理器有關的操作
//定位管理器的初始化
self.locationManager = [[AMapLocationManager alloc] init];
//設立定位管理器的委託
[self.locationManager setDelegate:self];

//設置期望定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];

//設置不允許系統暫停定位
[self.locationManager setPausesLocationUpdatesAutomatically:NO];

//設置允許在後臺定位
[self.locationManager setAllowsBackgroundLocationUpdates:YES];

//設置定位超時時間
[self.locationManager setLocationTimeout:DefaultLocationTimeout];

//設置逆地理超時時間
[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];

//停止定位
[self.locationManager stopUpdatingLocation];

[self.locationManager setDelegate:nil];

[self.mapView removeAnnotations:self.mapView.annotations];


//進行單次定位請求
[self.mapView removeAnnotations:self.mapView.annotations];
[self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];


//進行單次帶逆地理定位請求
[self.mapView removeAnnotations:self.mapView.annotations];
[self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];

/*
 --------------------------------------------------
 */

//-------------------地圖標註相關----------
//代理方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";

        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }

        annotationView.canShowCallout   = YES;
        annotationView.animatesDrop     = YES;
        annotationView.draggable        = NO;
        annotationView.pinColor         = MAPinAnnotationColorPurple;

        return annotationView;
    }

    return nil;
}

//定位點的添加
//用block來輔助

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
//對block的初始化
- (void)initCompleteBlock
{
    __weak SingleLocationViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);

            //如果爲定位失敗的error,則不進行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }

        //得到定位信息,添加annotation
        if (location)
        {
            MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
            [annotation setCoordinate:location.coordinate];

            if (regeocode)
            {
                [annotation setTitle:[NSString stringWithFormat:@"%@", regeocode.formattedAddress]];
                [annotation setSubtitle:[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
            }
            else
            {
                [annotation setTitle:[NSString stringWithFormat:@"lat:%f;lon:%f;", location.coordinate.latitude, location.coordinate.longitude]];
                [annotation setSubtitle:[NSString stringWithFormat:@"accuracy:%.2fm", location.horizontalAccuracy]];
            }

            SingleLocationViewController *strongSelf = weakSelf;
            [strongSelf addAnnotationToMapView:annotation];
        }
    };
}
//向地圖上添加標註
- (void)addAnnotationToMapView:(id<MAAnnotation>)annotation
{
    [self.mapView addAnnotation:annotation];

    [self.mapView selectAnnotation:annotation animated:YES];
    [self.mapView setZoomLevel:15.1 animated:NO];
    [self.mapView setCenterCoordinate:annotation.coordinate animated:YES];
}

//在進行定位請求的時候,請求標註的添加。
- (void)locAction
{
    [self.mapView removeAnnotations:self.mapView.annotations];

    //進行單次定位請求
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}


//-----------------------------------------------------



SingleLocationViewController.h
#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

@interface SingleLocationViewController : UIViewController

@property (nonatomic, strong) MAMapView *mapView;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@end

//----------------------------------------------

SingleLocationViewController.m
#import "SingleLocationViewController.h"

#define DefaultLocationTimeout  6
#define DefaultReGeocodeTimeout 3

@interface SingleLocationViewController () <MAMapViewDelegate, AMapLocationManagerDelegate>

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;

@end

@implementation SingleLocationViewController

#pragma mark - Action Handle

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];

    [self.locationManager setDelegate:self];

    //設置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];

    //設置不允許系統暫停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];

    //設置允許在後臺定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];

    //設置定位超時時間
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];

    //設置逆地理超時時間
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];

    [self.locationManager setDelegate:nil];

    [self.mapView removeAnnotations:self.mapView.annotations];
}

- (void)reGeocodeAction
{
    [self.mapView removeAnnotations:self.mapView.annotations];

    //進行單次帶逆地理定位請求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}

- (void)locAction
{
    [self.mapView removeAnnotations:self.mapView.annotations];

    //進行單次定位請求
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}

#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak SingleLocationViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);

            //如果爲定位失敗的error,則不進行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }

        //得到定位信息,添加annotation
        if (location)
        {
            MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
            [annotation setCoordinate:location.coordinate];

            if (regeocode)
            {
                [annotation setTitle:[NSString stringWithFormat:@"%@", regeocode.formattedAddress]];
                [annotation setSubtitle:[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
            }
            else
            {
                [annotation setTitle:[NSString stringWithFormat:@"lat:%f;lon:%f;", location.coordinate.latitude, location.coordinate.longitude]];
                [annotation setSubtitle:[NSString stringWithFormat:@"accuracy:%.2fm", location.horizontalAccuracy]];
            }

            SingleLocationViewController *strongSelf = weakSelf;
            [strongSelf addAnnotationToMapView:annotation];
        }
    };
}

- (void)addAnnotationToMapView:(id<MAAnnotation>)annotation
{
    [self.mapView addAnnotation:annotation];

    [self.mapView selectAnnotation:annotation animated:YES];
    [self.mapView setZoomLevel:15.1 animated:NO];
    [self.mapView setCenterCoordinate:annotation.coordinate animated:YES];
}

- (void)initMapView
{
    if (self.mapView == nil)
    {
        self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
        [self.mapView setDelegate:self];

        [self.view addSubview:self.mapView];
    }
}

- (void)initToolBar
{
    UIBarButtonItem *flexble = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                             target:nil
                                                                             action:nil];

    UIBarButtonItem *reGeocodeItem = [[UIBarButtonItem alloc] initWithTitle:@"帶逆地理定位"
                                                                      style:UIBarButtonItemStyleBordered
                                                                     target:self
                                                                     action:@selector(reGeocodeAction)];

    UIBarButtonItem *locItem = [[UIBarButtonItem alloc] initWithTitle:@"不帶逆地理定位"
                                                                style:UIBarButtonItemStyleBordered
                                                               target:self
                                                               action:@selector(locAction)];

    self.toolbarItems = [NSArray arrayWithObjects:flexble, reGeocodeItem, flexble, locItem, flexble, nil];
}

- (void)initNavigationBar
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Clean"
                                                                              style:UIBarButtonItemStyleBordered
                                                                             target:self
                                                                             action:@selector(cleanUpAction)];
}

#pragma mark - Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view setBackgroundColor:[UIColor whiteColor]];

    [self initToolBar];

    [self initNavigationBar];

    [self initMapView];

    [self initCompleteBlock];

    [self configLocationManager];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.navigationController.toolbar.translucent   = YES;
    self.navigationController.toolbarHidden         = NO;
}

- (void)dealloc
{
    [self cleanUpAction];

    self.completionBlock = nil;
}

#pragma mark - MAMapView Delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";

        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }

        annotationView.canShowCallout   = YES;
        annotationView.animatesDrop     = YES;
        annotationView.draggable        = NO;
        annotationView.pinColor         = MAPinAnnotationColorPurple;

        return annotationView;
    }

    return nil;
}




@end
發佈了53 篇原創文章 · 獲贊 22 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章