定位和反查位置信息要加载两个动态库 CoreLocation.framework 和 MapKit.framework 一个获取坐标一个提供反查,可以通过配置NSLocationAlwaysUsageDescription或者 NSLocationWhenInUseUsageDescription来告诉用户使用定位服务的目的,并且注意这个配置是必须的
import "ViewController.h"
import <UIKit/UIKit.h>
import <CoreLocation/CoreLocation.h>
import <MapKit/MapKit.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.self.button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.frame = CGRectMake(0, 100, 100, 30);
[_button setTitle:@"定位" forState:0];
[_button addTarget:self action:@selector(_startLocation) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
} -
(void)_startLocation {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = 10.0f;
[self.locationManager startUpdatingLocation];
[self.locationManager requestWhenInUseAuthorization];
}
实现locationManager的代理方法
-
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *newLocation = locations[0];
CLLocationCoordinate2D oCoordinate = newLocation.coordinate;
NSLog(@"经度:%f, 纬度: %f",oCoordinate.longitude,oCoordinate.latitude);
[self.locationManager stopUpdatingLocation];CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {for (CLPlacemark *place in placemarks) { NSDictionary *location = [place addressDictionary]; NSLog(@"国家:%@",[location objectForKey:@"Country"]); NSLog(@"城市:%@",[location objectForKey:@"State"]); NSLog(@"区:%@",[location objectForKey:@"SubLocality"]); NSLog(@"位置:%@",place.name); NSLog(@"国家:%@",place.country); NSLog(@"城市:%@",place.locality); NSLog(@"区:%@",place.subLocality); NSLog(@"街道:%@",place.thoroughfare); NSLog(@"子街道:%@",place.subThoroughfare); }
}];
}
网友评论