CoreLocationを使ってGPSやらなにやらで現在位置を特定する。
まずプロジェクトにCoreLocation.frameworkを追加する。
ここではサンプルとしてDemoViewControllerというものがあるとして、そこで位置取得を行う。
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface DemoViewController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *lm;
}
@end
viewDidLoad内であらかじめ位置取得の精度や頻度を設定することができる。
- (void)viewDidLoad
{
[super viewDidLoad];
lm = [[CLLocationMAnager alloc] init];
lm.delegate = self;
// 取得精度の指定
lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
// 取得頻度(指定したメートル移動したら再取得する)
lm.distanceFilter = 5; // 5m移動するごとに取得
}
- startUpdatingLocation
- stopUpdatingLocation
- (void)startLocation {
[lm startUpdatingLocation];
}
- (void)stopLocation {
[lm stopUpdatingLocation];
}
stopUpdatingLocationを実行してもすぐに停止しない。
しばらく待たなければ、ステータスの位置取得マークは消えない。
公式地図も他の地図アプリも同じ現象になるので、これはiOSというかiPhoneの仕様かと思われる。
以下のメソッドを用意しておくこと
- didUpdateToLocation
位置取得成功時 - didFailWithError
位置取得失敗時
// 現在地取得したら
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D coordinate;
coordinate.latitude = newLocation.coordinate.latitude;
coordinate.longitude = newLocation.coordinate.longitude;
// この緯度経度で何かやる・・・
}
// 現在地取得に失敗したら
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
[lm stopUpdatingLocation];
}
Apple公式Sample CodeにLocateMeというプロジェクトがある。
そこのGetLocationViewController.mに参考になるコードがあるから、是非一読を。