http://my.oschina.net/joanfen/blog/152136
摘要: 通过CoreLocation定位,获取到用户当前位置,跟地图中的定位不同,并计算两点之间的距离
一、导入CoreLocation.framework
二、#import <CoreLocation/CoreLocation.h>
三、声明代理 <CLLocationManagerDelegate>
四、代码实现
1、声明
01 |
CLLocationManager
*locationManager; |
03 |
if ([CLLocationManager
locationServicesEnabled]) { |
04 |
CLLocationManager
*locationManager = [[[CLLocationManager alloc] init] autorelease]; |
06 |
self.locationManager.delegate
= self; |
12 |
[locationManager
startUpdatingLocation]; |
2、更新位置后代理方法,iOS6.0一下的方法
01 |
-
( void )locationManager:(CLLocationManager
*)manager |
02 |
didUpdateToLocation:(CLLocation
*)newLocation |
03 |
fromLocation:(CLLocation
*)oldLocation { |
07 |
self.latitude
= [NSString stringWithFormat:@ "%.4f" ,
newLocation.coordinate.latitude]; |
10 |
self.longitude
= [NSString stringWithFormat:@ "%.4f" ,
newLocation.coordinate.longitude]; |
3、iOS6.0以上苹果的推荐方法
01 |
-( void )locationManager:(CLLocationManager
*)manager didUpdateLocations:(NSArray *)locations |
04 |
CLLocation
*currentLocation = [locations lastObject]; |
06 |
CLLocationCoordinate2D
coor = currentLocation.coordinate; |
07 |
self.latitude
= coor.latitude; |
08 |
self.longitude
= coor.longitude; |
4、更新失败的方法
1 |
-
( void )locationManager:(CLLocationManager
*)manager |
2 |
didFailWithError:(NSError
*)error { |
4 |
if (error.code
== kCLErrorDenied) { |
五、根据两点坐标计算两点之间的距离,此方法为苹果自带方法,亲测速度比高德API速度快很多,但是数据与高德API得到的不一样,准确度本人未能证实
2 |
CLLocation
*current=[[CLLocation alloc] initWithLatitude:32.178722 longitude:119.508619]; |
4 |
CLLocation
*before=[[CLLocation alloc] initWithLatitude:32.206340 longitude:119.425600]; |
6 |
CLLocationDistance
meters=[current distanceFromLocation:before]; |