1. XcodeでプロジェクトにCoreLocation.framework を追加する。
2. ヘッダファイルに CLLocationManagerDelegate の指定、 CoreLocation.frameworkのヘッダファイルを追加する。
RootViewController.h
#import <CoreLocation/CoreLocation.h>※<>は半角にすること。
@interface RootViewController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager; // 現在地情報取得
double latitude, longitude; // 取得した緯度経度
@property (nonatomic, retain) CLLocationManager *locationManager;
3. コード部分の編集
RootViewController.m
#import "RootViewController.h"
@synthesize names, locationManager;
■CLLocation呼び出し側メソッド
- (void)yobibashi {
// ロケーションマネージャ作成
if (nil == locationManager) {
locationManager = [[CLLocationManager alloc] init];
}
locationManager.delegate = self; // デリゲート設定
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 位置測定の望みの精度を設定
locationManager.distanceFilter = kCLDistanceFilterNone; // 位置情報更新の目安距離
// 現在地情報受信開始
[locationManager startUpdatingLocation];
}
■Locationデータ取得成功時
- (void)locationManager:(CLLocationManager *)managerdidUpdateToLocationメソッドは、Locationのデータがアップデートした際に呼ばれるので、複数回呼ばれることがある。従って、このメソッドの後続処理で画面遷移などを行う場合は、アップデート通知を1回のみにする必要がある。その実装は、locationManagerメソッド内でstopUpdatingLocationを呼び出せばよい。
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// 位置情報を取り出す
longitude = newLocation.coordinate.longitude;
latitude = newLocation.coordinate.latitude;
}
[locationManager stopUpdatingLocation];
■Locationデータ取得失敗時
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"エラー" message:@"位置情報が取得できませんでした。" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alertView show];
[alertView release];
}
■参考記事:
http://sites.google.com/a/gclue.jp/iphone-app-docs/iphoneapurinyuumon--gps
http://journal.mycom.co.jp/column/iphone/015/index.html
http://blog.cypher-works.com/?p=732
http://moyashi.air-nifty.com/hitori/2008/07/iphonesafari_go_f6a2.html
iPhoneで取得できる緯度経度は世界測地系(WGS84)。
日本測地系に変換する場合は、それほどの精度が必要でなければ近似値を出す簡単な変換式によって行う。
// 緯度経度を世界測地系(WGS84)から日本測地系に変換
double latitude_tokyo = latitude + 0.00010696 * latitude - 0.000017467 * longitude - 0.0046020;
double longitude_tokyo = longitude + 0.000046047 * latitude + 0.000083049 * longitude - 0.010041;
■参考記事
http://groups.google.com/group/Google-Maps-API-Japan/browse_thread/thread/d0ce529ce20edc4d/285aac6e0d3497a1
タグ:iPhone
【CLLocation 現在位置情報の最新記事】