標籤:
iOS地理位置使用經緯度介紹
英語不好,老是分不開這兩個單詞,在這記錄一下。
經度:longitude,豎線,(long有縱向之意,用來表示經度)
緯度:latitude,
使用
1.在項目匯入 CoreLocation.framework;
2.申請使用者授權(ios 8之後才需要)。在info.plist檔案中添加一個鍵:
NSLocationAlwaysUsageDescription或者NSLocationWhenInUseUsageDescription。其中NSLocationAlwaysUsageDescription是要始終使用定位服務,NSLocationWhenInUseUsageDescription是只在前台使用定位服務。
分別對應的授權方法為:
- (void)requestAlwaysAuthorization;- (void)requestWhenInUseAuthorization;
3.初始化,代碼如下:
//建立地理位置管理對象 self.locationManager = [[CLLocationManager alloc] init]; //申請授權 [self.locationManager requestAlwaysAuthorization]; //設定管理員委託 self.locationManager.delegate = self; //設定精度 self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //啟動位置管理器 [self.locationManager startUpdatingLocation];
4.實現委託方法
//地理位置發生更新時- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ //如果在一段比較短的時間發生了多次位置更新,這幾次位置更新有可能會被一次性全部上報。無論何時,最後一項表示當前位置 CLLocation *newLocation = [locations lastObject]; //顯示緯度 NSString *latitudeString = [NSString stringWithFormat:@"%g\u00B0",newLocation.coordinate.latitude]; self.latitudeLabel.text = latitudeString; //顯示經度 NSString *longitudeString = [NSString stringWithFormat:@"%g\u00B0",newLocation.coordinate.longitude]; self.longitudeLabel.text = longitudeString; //顯示水平精度 NSString *horizontalAccuracyString = [NSString stringWithFormat:@"%gm",newLocation.horizontalAccuracy]; self.horizontalAccuracyLabel.text = horizontalAccuracyString; //顯示海拔高度 NSString *altitudeString = [NSString stringWithFormat:@"%gm",newLocation.altitude]; self.altitudeLabel.text = altitudeString; //顯示垂直精度 NSString *verticalAccuracyString = [NSString stringWithFormat:@"%gm",newLocation.verticalAccuracy]; self.verticalAccuracyLabel.text = verticalAccuracyString; if (newLocation.verticalAccuracy < 0 || newLocation.horizontalAccuracy < 0) { return; } if (newLocation.horizontalAccuracy > 100 || newLocation.verticalAccuracy > 50) { return; } if (self.previousPoint == nil) { return; } else { self.totalMovementDistance += [newLocation distanceFromLocation:self.previousPoint]; } self.previousPoint = newLocation; NSString *distanceString = [NSString stringWithFormat:@"%gm",self.totalMovementDistance]; self.distanceTraveledLabel.text = distanceString;}//擷取地理位置失敗時- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ NSString *errorType = (error.code == kCLErrorDenied) ? @"Access Denied": @"Unknown Error"; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error getting Location" message:errorType delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil]; [alert show];}
代碼下載
https://github.com/limaofuyuanzhang/WhereAmI
參考
iOS定位服務的應用
《精通iOS開發(第6版)》第19章 Core Location和Map Kit
iOS地理位置使用