Map1: iOS开发中定位和地图介绍

 
Core Location 以及 Map 框架包通常能给我们的应用程序添加定位和地图相关的服务。
Core Location 框架包通常是使用硬件设备来进行定位服务的,Map 框架包通常能够使你的应用程序做一些地图展示与交互的相关功能。 
一.准备
为了能够在项目中使用到位置服务以及地图展示的相关功能,你必须要导入 Core Location 和 Map 这两个框架包:
1.点击你的项目工程图标文件
2.然后选择 target 选项
3.然后选择 Build Phase 模块栏
4.然后点开 Link Binary With Libraries 栏目,再点击+号按钮
5.在对话框中你将看到所有支持的框架和静态库,找到并选择 CoreLocation 和 Mapkit框架然后按下添加 
 
在添加完这两个包之后,你需要在你的.h 文件或.m 文件中添加头文件的引用(在你的头文件中如果有涉及任何有关于这两个框架的引用)。  
#import <CoreLocation/CoreLocation.h> 
#import <MapKit/MapKit.h>

二.下面创建一个地图的视图

往你的程序中添加一个地图展示的功能。 

 .h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface mapViewController : UIViewController

@property (nonatomic, strong)MKMapView *myMapView;

@end

.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    //初始化map
    self.myMapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
    //设置地图类型
    self.myMapView.mapType = MKMapTypeStandard;
    self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_myMapView];
}
我们可以通过 MKMapView 的 mapType 属性来切换地图的展现形式。有如下的属性值可用:

MKMapTypeStandard  显示普通地图(这个是默认的)。

MKMapTypeSatellite    显示卫星云图。

MKMapTypeHybrid      显示普通地图覆盖于卫星云图之上,这个地图的展现形式属于复合形式。 

三.处理Map视图上的事件

map 视图可以将事件发送给它的 delegate 来处理事件
将遵循 MKMapViewDelegate 协议的 delegate 对象赋值给 MKMapView 实例对象的 delegate 属性。 
self.myMapView.delegate = self;

四.精确定位设备的位置

使用 CLLocationManager 这个类,参考代码如下 

注意: 

Core Location 框架提供了让开发者能够利用 iOS 设备来进行位置服务。因为在 iOS 中,用户是可以通过设置程序来禁用位置服务的,因此,当你在使用 CLLocationManager 这个类的时候,最好首先判断一下设备中的位置服务是否可用。 

//地图定位,CLLocation
    
    //当你在使用 CLLocationManager 这个类的时候,最好首先判断一下设备中的位置服务是否可用。
    if ([CLLocationManager locationServicesEnabled]) {
        _myLocationManager = [[CLLocationManager alloc]init];
        _myLocationManager.delegate = self;
        //开始更新位置
        [_myLocationManager startUpdatingLocation];
    }else{
        NSLog(@"Location services are not enabled");
    }
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //我们收到了新的位置
    NSLog(@"locations = %@",locations);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    //获取位置失败
    NSLog(@"error = %@",error);
}
如上代码,CLLocationManager 的 startUpdateLocation 方法通过它的代理locationManager:didUpdateLocation: 和 locationManager:didFailWithError:方法来报告用户定位成功或失败。 

 

 

 

 

 

 

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。