電子趣味の部屋

電子系のガジェットやアプリ開発等の趣味の話題を書いてます

iPhoneのGPSとMapKitを使った地図を連動させる方法

前回のエントリー"iPhoneで緯度経度を取得する簡単な方法の続き。
今度は取得した座標を中心に地図を表示させるメモです。
前回のプロジェクトに追加します。

プロジェクトへMapKit.Frameworkを追加


"<プロジェクト名>AppDelegate.h"へヘッダファイルとプロトコルの追加する際の例

・"MapKit/MKMapView.h" をインポートする。
プロトコルへ"MKMapViewDelegate"を追加する。

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MKMapView.h>

@interface testGPSAppDelegate : NSObject <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate> {
    UIWindow *window;
	MKMapView *mapview;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

<プロジェクト名>AppDelegate.m"で処理する際の例

・MKMapViewのインスタンスを作成し、初期化処理をする。
・位置情報の取得に成功した場合はの処理(didUpdateToLocation)で取得した座標を中心に地図を表示する処理を追加。

#import "testGPSAppDelegate.h"

@implementation testGPSAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    [window makeKeyAndVisible];
	
	// MKMapViewのインスタンスを作成
	mapview = [[MKMapView alloc] initWithFrame:window.bounds];
	mapview.delegate = self;
	
	// windowにMKMapViewを追加
	[window addSubview:mapview];
	
	// CLLocationManagerのインスタンスを作成
	CLLocationManager *locationManager = [[CLLocationManager alloc] init];
	if ([locationManager locationServicesEnabled]) {
		// ロケーションサービスが利用できる場合
		locationManager.delegate = self;
		[locationManager startUpdatingLocation];
	} else {
		// ロケーションサービスが利用できない場合
	}
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	// 緯度経度取得に成功した場合
	CLLocationCoordinate2D coordinate = newLocation.coordinate;
	
	// 取得した座標を中心に地図を表示
	[mapview setCenterCoordinate:coordinate animated:NO];

	// 縮尺を設定
	MKCoordinateRegion zoom = mapview.region;
	zoom.span.latitudeDelta = 0.005;
	zoom.span.longitudeDelta = 0.005;
	[mapview setRegion:zoom animated:YES];

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
	// 緯度経度取得に失敗した場合
}

- (void)dealloc {
    [window release];
    [mapview release];
    [super dealloc];
}

@end

これでアプリが起動して座標を取得できたら、地図が表示される。

レイ・アウト iPhone 3G ケース 大容量バッテリー内蔵本革レザージャケット RT-P1BT1/B

レイ・アウト iPhone 3G ケース 大容量バッテリー内蔵本革レザージャケット RT-P1BT1/B