1. 程式人生 > >iOS獲取當前位置經緯度

iOS獲取當前位置經緯度

最近在做一個公交車查詢的專案,需要定位到當前位置以便進行附近站點查詢,和大家分享一下怎樣獲取自己當前位置的經緯度

首先新增CoreLocation.framework庫:


引用標頭檔案並宣告CLLocationManagerDelegate代理:

接下來宣告要用到的變數:

@property (strong, nonatomic) CLLocationManager *locManager;
@property (strong, nonatomic) CLLocation *checkinLocation;
@property (strong, nonatomic) NSString *currentLatitude; //緯度
@property (strong, nonatomic) NSString *currentLongitude; //經度

在viewDidLoad中判斷使用者是否啟用定位服務,第一次進入應用時系統會提示是否啟用定位操作。然後開始定位當前位置:

if ([CLLocationManager locationServicesEnabled]) {
        self.locManager = [[CLLocationManager alloc] init];
        self.locManager.delegate = self;
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"無法進行定位操作" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
        [alert show];
    }
    [self.locManager startUpdatingLocation];

呼叫代理方法更新當前位置:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    self.checkinLocation = [locations lastObject];
    CLLocationCoordinate2D cool = self.checkinLocation.coordinate;
    self.currentLatitude  = [NSString stringWithFormat:@"%.4f",cool.latitude];
    self.currentLongitude = [NSString stringWithFormat:@"%.4f",cool.longitude];
    
    NSLog(@"%@,%@",self.currentLatitude,self.currentLongitude);
}

執行程式,控制檯也輸出了當前位置的經緯度(遮住地址,寫的不好你們也找不到我):


第一次寫部落格,希望能對大家有所幫助,有錯誤和不足的地方希望大家能提提意見,學習的路上與大家共勉,我可是勵志要成為火星猿的男人!