Skip to content

Instantly share code, notes, and snippets.

@nantekkotai
Created May 31, 2012 07:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nantekkotai/2841743 to your computer and use it in GitHub Desktop.
Save nantekkotai/2841743 to your computer and use it in GitHub Desktop.
[iOS]CoreLocationで現在位置を取得する

CoreLocationを使ってGPSやらなにやらで現在位置を特定する。

Frameworkの追加

まずプロジェクトにCoreLocation.frameworkを追加する。

使用するファイルにimport

ここではサンプルとして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に参考になるコードがあるから、是非一読を。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment