[ iOS ] 取得座標,與某地的距離

取得座標

info 設定權限:
  • NSLocationWhenInUseUsageDescription 使用期間使用
  • NSLocationAlwaysUsageDescription 總是使用
.h檔import

#import 
#import 
@interface ViewController : UIViewController 

取得位置:
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    lc = [CLLocationManager new];
    lc.desiredAccuracy = kCLLocationAccuracyBest;
    lc.delegate = self;
    
    [lc requestWhenInUseAuthorization];
    [lc startUpdatingLocation];
}
//回傳位置 location 是一個陣列  
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    NSLog(@"%@",locations);
    CLLocation *userLocation = [locations lastObject];
    CLLocation *church = [[CLLocation alloc] initWithLatitude: 37.78583400 longitude:122.40641700];
    double distance = [userLocation distanceFromLocation:church];
}
  • 因為為了避免在手機繁忙的時候遺漏座標, locationManager 方法會一直有新座標加進來,locationManager來跟gps要位置的時候,會一次拿走所以的座標

留言