iOS的原声定位以来CoreLocation和MapKit框架
在iOS8以后执行定位操作需要在info.plst添加两个关键字段NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription如下图:
在需要定位的地方导入#import <CoreLocation/CoreLocation.h>
//开始定位
-(void)startLocation{
//判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init] ;
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
self.locationManager.distanceFilter=kCLDistanceFilterNone;
[self.locationManager startUpdatingLocation];
}else {
//提示用户无法进行定位操作
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
@"提示"message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
[alertView show];
}
}
//定位的回调方法,
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *oldLocation = locations[0];
CLLocationCoordinate2D oldCoordinate = oldLocation.coordinate;
DLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);
[manager stopUpdatingLocation]; //停止定位 。
CLLocation* curLocation = [[CLLocation alloc] initWithLatitude:116.396566 longitude:39.930309];
CLLocation* otherLocation = [[CLLocation alloc] initWithLatitude:116.394158 longitude:39.929957];
double distance = [curLocation distanceFromLocation:otherLocation];
NSLog(@"%f",distance);
//------------------位置反编码---5.0之后使用-----------------
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:oldLocation
completionHandler:^(NSArray *placemarks, NSError *error){
for (CLPlacemark *place in placemarks) {
// UILabel *label = (UILabel *)[self.window viewWithTag:101];
// label.text = place.name;
NSLog(@"name,%@",place.name); // 位置名
NSLog(@"thoroughfare,%@",place.thoroughfare); // 街道
NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
NSLog(@"locality,%@",place.locality); // 市
NSLog(@"subLocality,%@",place.subLocality); // 区
NSLog(@"country,%@",place.country); // 国家
}
}];
}
警告:在模拟器定位需要给模拟器一个位置。
计算两个坐标点之间的距离
CLLocation* curLocation = [[CLLocation alloc] initWithLatitude:116.396566 longitude:39.930309];
CLLocation* otherLocation = [[CLLocation alloc] initWithLatitude:116.394158 longitude:39.929957];
double distance = [curLocation distanceFromLocation:otherLocation];
默认单位为米。