GPSから緯度と経度を取得し、矢印が必ず北を向くコンパスを作成します。
ViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| #import <UIKit/UIKit.h>
//CoreLocationフレームワークを読み込む
#import <CoreLocation/CoreLocation.h>
//UIViewControllerを CLLocatinManagerのデリゲートに指定
@interface ViewController : UIViewController <CLLocationManagerDelegate> {
//CLLocationManagerを定義
CLLocationManager *lm;
}
//緯度を表示するラベル
@property (weak, nonatomic) IBOutlet UILabel *latLabel;
//経度を表示するラベル
@property (weak, nonatomic) IBOutlet UILabel *lngLabel;
//コンパス用の上向き矢印画像 (Storyboardに配置)
@property (weak, nonatomic) IBOutlet UIImageView *compass;
@end
|
ViewController.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
| #import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//初期化
lm = [[CLLocationManager alloc] init];
//デリゲートに selfを指定
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyHundredMeters;
lm.distanceFilter = kCLDistanceFilterNone;
//緯度と経度のアップデート開始
[lm startUpdatingLocation];
//コンパスのアニメーション開始
[lm startUpdatingHeading];
}
//緯度と経度をアップデートし、ラベルテキストに代入する
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//緯度のラベルテキストを更新
self.latLabel.text = [NSString stringWithFormat:@"緯度=%g", newLocation.coordinate.latitude];
//経度のラベルテキストを更新
self.lngLabel.text = [NSString stringWithFormat:@"軽度=%g", newLocation.coordinate.longitude];
}
//北を向くコンパスの矢印を回転させる
- (void)locationManager:(CLLocationManager *)manager
didUpdateHeading:(CLHeading *)heading {
self.compass.transform = CGAffineTransformMakeRotation(-heading.magneticHeading * M_PI/180);
}
@end
|
お薦めの参考書
詳解 Swift 改訂版
Swiftのかなり入り込んだところまで解説しながら、実践コードを多数収録しています。応用本になりますので、入門書を読み終えて中級者から上級者に差し掛かる時に読むことをお勧めします。読み物としてだけではなくリファレンスとしても使用できます。