分享

定位-计算距离

 稀世珍藏 2016-03-29
 一、导入CoreLocation.framework  二、#import <CoreLocation/CoreLocation.h>
三、声明代理 <CLLocationManagerDelegate>
四、代码实现
1、声明
  1. CLLocationManager *locationManager;//定义Manager
  2. // 判断定位操作是否被允许
  3. if([CLLocationManager locationServicesEnabled]) {
  4.     CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];

  5.      self.locationManager.delegate = self;
  6. }else {
  7.      //提示用户无法进行定位操作
  8. }

  9. // 开始定位
  10. [locationManager startUpdatingLocation];
复制代码
2、更新位置后代理方法,iOS6.0一下的方法
  1. - (void)locationManager:(CLLocationManager *)manager
  2.     didUpdateToLocation:(CLLocation *)newLocation
  3.            fromLocation:(CLLocation *)oldLocation {

  4.         //latitude和lontitude均为NSString型变量
  5.         //纬度
  6.         self.latitude = [NSString  stringWithFormat:@"%.4f", newLocation.coordinate.latitude];

  7.         //经度
  8.         self.longitude = [NSString stringWithFormat:@"%.4f",                                                    newLocation.coordinate.longitude];
  9.        
  10. }
复制代码
3、iOS6.0以上苹果的推荐方法
  1. -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
  2. {
  3.     //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
  4.     CLLocation *currentLocation = [locations lastObject];
  5.    
  6.     CLLocationCoordinate2D coor = currentLocation.coordinate;
  7.     self.latitude =  coor.latitude;
  8.     self.longitude = coor.longitude;
  9.    
  10.     //[self.locationManager stopUpdatingLocation];
  11.    
  12. }
复制代码
4、更新失败的方法
  1. - (void)locationManager:(CLLocationManager *)manager
  2.        didFailWithError:(NSError *)error {
  3.        
  4.   if (error.code == kCLErrorDenied) {
  5.       // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
  6.   }
  7. }
复制代码
五、根据两点坐标计算两点之间的距离,此方法为苹果自带方法,亲测速度比高德API速度快很多,但是数据与高德API得到的不一样,准确度本人未能证实
  1. //第一个坐标
  2. CLLocation *current=[[CLLocation alloc] initWithLatitude:32.178722 longitude:119.508619];
  3. //第二个坐标
  4. CLLocation *before=[[CLLocation alloc] initWithLatitude:32.206340 longitude:119.425600];
  5. // 计算距离
  6. CLLocationDistance meters=[current distanceFromLocation:before];
复制代码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多