在iOS开发中自动获取当前的位置(GPS定位)
代码的下载连接http://download.youkuaiyun.com/detail/jingjingxujiayou/7154113
开发环境 xcode5.0
首先我们要引入这个框架CoreLocation.framework
将这个库引进来#import <CoreLocation/CoreLocation.h>
还有他的代理方法 CLLocationManagerDelegate
GPSViewController.h
注意这里的CLLocationManager* locationmanager要设置成全局变量,要不然得不到你想要的结果哦!具体为什么,我现在还不清楚
1
2
3
4
5
6
|
#
import
<
UIKit
/
UIKit
.
h
>
#
import
<
CoreLocation
/
CoreLocation
.
h
>
@interface
GPSViewController
:
UIViewController
<CLLocationManagerDelegate>
@property
(
nonatomic
,
retain
)
CLLocationManager
*
locationmanager
;
@end
|
GPSViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
#
import
"GPSViewController.h"
@interface
GPSViewController
(
)
@end
@implementation
GPSViewController
@synthesize
locationmanager
;
-
(
id
)
initWithNibName
:
(
NSString
*
)
nibNameOrNil
bundle
:
(
NSBundle
*
)
nibBundleOrNil
{
self
=
[
super
initWithNibName
:
nibNameOrNil
bundle
:
nibBundleOrNil
]
;
if
(
self
)
{
// Custom initialization
}
return
self
;
}
-
(
void
)
viewDidLoad
{
[
super
viewDidLoad
]
;
// Do any additional setup after loading the view.
locationmanager
=
[
[
CLLocationManager
alloc
]
init
]
;
//设置精度
/*
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers
*/
//设置定位的精度
[
locationmanager
setDesiredAccuracy
:
kCLLocationAccuracyBest
]
;
//实现协议
locationmanager
.
delegate
=
self
;
NSLog
(
@
"开始定位"
)
;
//开始定位
[
locationmanager
startUpdatingLocation
]
;
}
-
(
void
)
locationManager
:
(
CLLocationManager
*
)
manager
didUpdateToLocation
:
(
CLLocation
*
)
newLocation
fromLocation
:
(
CLLocation
*
)
oldLocation
{
NSLog
(
@
"hello"
)
;
//打印出精度和纬度
CLLocationCoordinate2D
coordinate
=
newLocation
.
coordinate
;
NSLog
(
@
"输出当前的精度和纬度"
)
;
NSLog
(
@
"精度:%f 纬度:%f"
,
coordinate
.
latitude
,
coordinate
.
longitude
)
;
//停止定位
[
locationmanager
stopUpdatingLocation
]
;
//计算两个位置的距离
float
distance
=
[
newLocation
distanceFromLocation
:
oldLocation
]
;
NSLog
(
@
" 距离 %f"
,
distance
)
;
}
@end
|