iOS中的图中怎么计算两点间的距离

通过CoreLocation定位,获取到用户当前位置,跟地图中的定位不同,并计算两点之间的距离

一、导入CoreLocation.framework

 二、#import <CoreLocation/CoreLocation.h> 

三、声明代理 <CLLocationManagerDelegate>

1、声明 

CLLocationManager *locationManager;//定义Manager 

// 判断定位操作是否被允许

 if([CLLocationManager locationServicesEnabled]) { CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease]; self.locationManager.delegate = self; 

}

else {

 //提示用户无法进行定位操作

 } 

// 开始定位

 [locationManager startUpdatingLocation]; 

2、更新位置后代理方法,iOS6.0一下的方法 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 

//latitude和lontitude均为NSString型变量 

//纬度

 self.latitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.latitude]; 

//经度 

self.longitude = [NSString stringWithFormat:@"%.4f", newLocation.coordinate.longitude]; 

}

 3、iOS6.0以上苹果的推荐方法 

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { 

//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation 

CLLocation *currentLocation = [locations lastObject]; CLLocationCoordinate2D coor = currentLocation.coordinate; self.latitude = coo.latitude;

 self.longitude = coo.longitude;

 //[self.locationManager stopUpdatingLocation];

 } 

4、更新失败的方法 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

 if (error.code == kCLErrorDenied) {

 // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在

 } 

}

 五、根据两点坐标计算两点之间的距离,此方法为苹果自带方法,亲测速度比高德API速度快很多,但是数据与高德API得到的不一样

 //第一个坐标

 CLLocation *current=[[CLLocation alloc] initWithLatitude:32.178722 longitude:119.508619]; 

//第二个坐标

 CLLocation *before=[[CLLocation alloc] initWithLatitude:32.206340 longitude:119.425600]; 

// 计算距离 

CLLocationDistance meters=[current distanceFromLocation:before];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值