1. 定位三种方式: GPS,WIFI, 蜂窝数据(系统决定优先顺序,用户无法干预)
2. 系统的定位库: CoreLocation : CLLocationManager
3.ios8 中定位功能的改变:
需要 CLLocationManager 去申请权限
info.plist 中配置
4. 定位成功后,会一直更新位置:位置是不够精确的,使位置更为精确,如果没有停止定位,会一直更新
5. 经纬度 typedef struct {
CLLocationDegrees latitude;
CLLocationDegrees longitude;
} CLLocationCoordinate2D;
6. 反编码: reverseGeocodeLocation 经纬度 -> 详细信息
7. 编码: geocodeAddressString 详细信息 -> 经纬度
定位管理器 用到的类: CLLocationManager :NSObject
获取当前位置 用到的类: CLLocation : NSObject < NSCopying , NSSecureCoding >
首先需要实现定位管理器这个类 然后设置委托 然后设置在 App 运行状态下允许定位
self . locationManager = [[ CLLocationManager alloc ] init ];
self . locationManager . delegate = self ;
// 一直 使用定位功能
// [self.locationManager requestAlwaysAuthorization];
// 应用使用期间 使用定位功能
[ self . locationManager requestWhenInUseAuthorization ];
// 并在 info.plist 文件中配置数据
![屏幕快照 2016-03-05 10.03.59.png](https://app.yinxiang.com/shard/s47/res/45ed9741-4bb0-4bf4-b4d1-d43e14f62b3d.png)
// 开始定位
[ self . locationManager startUpdatingLocation ];
delegate — 定位委托方法
- ( void )locationManager:( CLLocationManager *)manager
didUpdateLocations:( NSArray *)locations{
NSLog ( @" 获取到位置 %@" ,locations[ 0 ]);
if (locations) {
// 定位偏移
self . uLocation = [locations lastObject ];
// 停止定位
[ self . locationManager stopUpdatingLocation ];
// 反编码:
[ self getLocationInfo : self . uLocation ];
// 测试编码
// [self getLocationCoord:@" 中国河南省郑州市河南通信产业园 "];
// 显示定位到的信息
// self.addInfoLabel.text = [NSString stringWithFormat:@" 经纬度: %f-%f",self.uLocation.coordinate.latitude,self.uLocation.coordinate.longitude];
}
}
// 定位失败
- ( void )locationManager:( CLLocationManager *)manager
didFailWithError:( NSError *)error;
{
NSLog ( @" 定位失败 %@" ,error);
switch (error. code ) {
case kCLErrorLocationUnknown :
NSLog ( @" 定位失败 : 未知错误 %@" ,error);
break ;
case kCLErrorDenied :
NSLog ( @" 定位失败:用户拒绝 %@" ,error);
break ;
default :
break ;
}
}
反编码 测试编码 ————方法封装后再获取位置的委托方法中调用
-( void ) getLocationInfo:( CLLocation *) location
{
CLGeocoder * geoCoder = [[ CLGeocoder alloc ] init ];
[geoCoder reverseGeocodeLocation :location completionHandler :^( NSArray *placemarks, NSError *error) {
if (!error && [placemarks count ]> 0 ) {
CLPlacemark * placeMark = [placemarks firstObject ];
self . addInfoLabel . text = placeMark. locality ;
}
}];
}
-( void ) getLocationCoord:( NSString *) addr
{
// addr = @" 中国河南省郑州市经开区第五大街 ";
addr = @" 中国河南省郑州市郑州东站 " ;
CLGeocoder * coder = [[ CLGeocoder alloc ] init ];
[coder geocodeAddressString :addr completionHandler :^( NSArray *placemarks, NSError *error) {
if (!error && [placemarks count ]> 0 ) {
CLPlacemark * placeMark = [placemarks firstObject ];
CLLocationCoordinate2D coord = placeMark. location . coordinate ;
self . addInfoLabel . text = [ NSString stringWithFormat : @" 经纬度: %f-%f" ,coord. latitude ,coord. longitude ];
}
}];
}