專案中常需要用手機定位取得經緯度,再上傳給後台。以下示範在 iOS 8 中如何取得定位並轉換為地名。
首先導入 CoreLocation 與 MapKit 框架:
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
定義定位管理器屬性並實作 CLLocationManagerDelegate:
@property(nonatomic,retain) CLLocationManager *locationManager;
開始定位:
-(void)getLocationAll
{
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager requestAlwaysAuthorization]; // iOS 8 需加上這句
[_locationManager startUpdatingLocation];
}
取得位置後,透過 CLGeocoder 反向地理編碼取得地址:
CLLocationCoordinate2D coordinate;
coordinate.latitude = [jingduStr floatValue];
coordinate.longitude = [weiduStr floatValue];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray* placemarks, NSError* error)
{
MKPlacemark *placemark = [placemarks objectAtIndex:0];
LocationAddress = [NSString stringWithFormat:@"%@%@%@%@", placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.subThoroughfare];
}];
實作代理方法取得位置資料:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
jingduStr = [NSString stringWithFormat:@"%f", currLocation.coordinate.latitude];
weiduStr = [NSString stringWithFormat:@"%f", currLocation.coordinate.longitude];
[self change];
}
並在取得位置後呼叫 stopUpdatingLocation 停止持續更新,避免浪費電力。