CoreLocation.framework 定位要用到這個框架
import <CoreLocation/CoreLocation.h>
info 設(shè)置 NSLocationWhenInUseUsageDescription boolean YES
創(chuàng)建對象 》設(shè)置代理 >設(shè)置》開的更新位置
@property (nonatomic,strong) CLLocationManager * manger;
// ios8要定位,要請求定位的權(quán)限
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
[manager requestWhenInUseAuthorization];
}
//完整代碼
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager * manger;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1>CLLocationManager對象
CLLocationManager *manager = [[CLLocationManager alloc] init];
// 設(shè)置代理
manager.delegate = self;
// 距離過濾 設(shè)置多少米定位一次
manager.distanceFilter = 1000;
// 設(shè)置定位的精確度刮刑,誤差不超過10米,定位越精確魁袜,越耗電
manager.desiredAccuracy = 10;
//2>調(diào)用 startUpdatingLocation方法進(jìn)入定位
[manager startUpdatingLocation];
// ios8要定位,要請求定位的權(quán)限
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
[manager requestWhenInUseAuthorization];
}
//賦值
self.manger = manager;
}
#pragma mark 定位到經(jīng)緯后調(diào)用
/*
* 這方法調(diào)用非常頻煩,時(shí)刻定位你當(dāng)前的位置
* 導(dǎo)航時(shí)需要時(shí)刻定位炮沐,但是争群,只是獲取當(dāng)前位置信息,不需要時(shí)時(shí)定位
*/
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
// CLLocation 是一個位置對象
for (CLLocation *loc in locations) {
// 經(jīng)緯度
CLLocationCoordinate2D coordinate = loc.coordinate;
NSLog(@"定位到經(jīng)度 %lf,緯度 %lf",coordinate.longitude,coordinate.latitude);
// 當(dāng)前位置是廣州大年,計(jì)算距離北京距離,單位是米 / 1000
CLLocation *bjLocation = [[CLLocation alloc] initWithLatitude:23.05 longitude:113.15];
double distance = [loc distanceFromLocation:bjLocation];
NSLog(@"當(dāng)前位置與北京的距離 %lf 公里",distance / 1000);
}
// 停止定位
[manager stopUpdatingLocation];
}
@end