//
// CoreLocationViewController.m
// CoreLocation
//
// Created by xiaoyao on 15/3/23.
// Copyright (c) 2015年 lije. All rights reserved.
//
#import "CoreLocationViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface CoreLocationViewController () <CLLocationManagerDelegate> {
CLLocationManager *_locationManager;
CLGeocoder *_geocoder;
}
@end
@implementation CoreLocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建定位管理器对象
_locationManager = [[CLLocationManager alloc] init];
if (![_locationManager locationServicesEnabled]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"是否允许启动定位服务"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定", nil];
[alertView show];
}
// 如果定位服务状态未授权的话进行授权
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
[_locationManager requestWhenInUseAuthorization];
} else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways){
// 设为使用应用程序的时候进行定位状态
_locationManager.delegate = self;
// 定位精度
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 定位频率
CLLocationDistance distance = 10.0f;
_locationManager.distanceFilter = distance;
// 开始追踪定位
[_locationManager startUpdatingLocation];
} else {
NSLog(@"尚未开启定位服务");
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[_locationManager stopUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
for (int i = 0; i < locations.count; i++) {
CLLocation *loction = [locations objectAtIndex:i];
CLLocationCoordinate2D coor = loction.coordinate;
NSLog(@"经度= %f, 纬度= %f, 海拔= %f, 航向=%f,行走速度=%f",coor.longitude,coor.latitude,loction.altitude,loction.course,
loction.speed);
[self getAddressByLocation:loction];
}
// 如果不需要时时定位,则定位一次完成关闭定位
[_locationManager stopUpdatingLocation];
}
// 根据地理位置得到地理名称
- (void)getAddressByLocation:(CLLocation *)loction {
[_geocoder reverseGeocodeLocation:loction completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *place = [placemarks firstObject];
NSDictionary *dict = place.addressDictionary;
[self getCoordinateByAddress:dict];
NSLog(@"%@", dict);
}];
}
// 根据地理坐标得到地理名称
- (void)getCoordinateByAddress:(NSDictionary *)addressDict {
[_geocoder geocodeAddressDictionary:addressDict completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *place = [placemarks firstObject];
CLLocation *loction = place.location;
CLRegion *region = place.region;
NSLog(@"%@%@",loction, region);
}];
}
@end
地理编码与反地理编码
最新推荐文章于 2018-07-08 15:58:22 发布