iPhoneによる位置情報関係のまとめ

以下はiPhoneによる位置情報関係のまとめ | アクトインディ技術部隊報告書と同様のものです。

今回も前回のGeohashに引き続き、位置情報に関する内容です。
ググれば出てくる内容なので、新しいことはなんにもないのが申し訳ないところです。

位置情報に関するライブラリは

  • CoreLocation
  • MapKit

などがあります。

GPSで現在位置を取得するにはCoreLocationを使用し、地図を表示したり現在地の大まかな住所を取得するためにはMapKitを使用します。

GPSで現在位置を取得するには

CoreLocationではCLLocationManagerDelegateを実装し

- (void)setup
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    if ([locationManager locationServicesEnabled])
    {
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [locationManager setDistanceFilter:kCLDistanceFilterNone];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"%@", newLocation);
}

このようにすればLogに現在地の情報が取得できます。

地図を表示するには

- (void)setup
{
    CGRect screen = [[UIScreen mainScreen] bounds];
    MKMapView *mapView = [[MKMapView alloc] initWithFrame:screen];
    [[self view] addSubview:mapView];
    [mapView release];

    MKCoordinateRegion  region;
    region.center = [location coordinate];
    region.span.latitudeDelta = 0.005;
    region.span.longitudeDelta = 0.005;
    [mapView setRegion:region animated:YES];
}

とすれば、locationで指定した座標に移動します。

現在地を取得するには

MKReverseGeocoderDelegateを実装し

- (void)setup
{
    MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[location coordinate]];
    [reverseGeocoder setDelegate:self];
    [reverseGeocoder start];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    NSLog(@"%@", [placemark title]);
}

とすることで取得することができます。
すべてのAPIが非常にシンプルに作られているので、使用するのは非常に簡単です。