声明:iOS开发小白程序员一枚,正在新手上路级别,行文中如有错误,还望各位批评指正,谢谢^^
效果图如下:
实现代码如下:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface LocationViewController : UIViewController<CLLocationManagerDelegate>
@property (strong,nonatomic)CLLocationManager *locationManager;
@end
#import "LocationViewController.h"
@implementation LocationViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0, 100, 320, 30);
[button setTitle:@"开始定位" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 160, 30)];
label1.tag = 101;
[self.view addSubview:label1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(160, 200, 160, 30)];
label2.tag = 102;
[self.view addSubview:label2];
}
- (void)buttonClicked:(UIButton *)sender
{
//使用iOS自带定位服务,需要导入CoreLocation.framework库,同时导入#import <CoreLocation/CoreLocation.h>
//初始化位置服务
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
//设置位置变化多少米调用一次代理方法(不是一直在调用,而是有了多少米距离的变化才调用)
[locationManager setDistanceFilter:1.0f];
/**
设置定位精度,精度越高越费电
kCLLocationAccuracyBestForNavigation -- 最高精度,需要连接电源时可用
kCLLocationAccuracyBest -- 最高精度
kCLLocationAccuracyNearestTenMeters -- 10米范围内
kCLLocationAccuracyHundredMeters -- 100米范围内
kCLLocationAccuracyKilometer -- 1000米范围内
kCLLocationAccuracyThreeKilometers -- 3000米范围内
*/
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
//设置代理
locationManager.delegate = self;
//开始定位
[locationManager startUpdatingLocation];
//在ARC下必须使用个属性存起来,否则会被释放掉,导致“程序要使用您当前的位置”提示框闪一下便消失,无法点击确定
self.locationManager = locationManager;
}
#pragma mark - CLLocationManagerDelegate
//定位成功调用的代理协议,此协议是不断调用的
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//创建经纬度结构体对象,其中newLocation为现在位置,oldLocation为上次位置
CLLocationCoordinate2D coord2D = newLocation.coordinate;
UILabel *label1 = (UILabel *)[self.view viewWithTag:101];
label1.text = [NSString stringWithFormat:@"经度:%f",coord2D.longitude];
UILabel *label2 = (UILabel *)[self.view viewWithTag:102];
label2.text = [NSString stringWithFormat:@"纬度:%f",coord2D.latitude];
NSLog(@"经度:%f--纬度:%f",coord2D.longitude,coord2D.latitude);
//一般使用定位1次即可,所以在使用之后将定位服务关闭以节省电量
[self.locationManager stopUpdatingLocation];
}
//定位失败调用的代理协议
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"定位出错");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
demo下载地址 点击这里下载demo