マップの表示
位置座標を取得するだけでも役には立ちますが、その位置を地図上で視覚的に確認できれば、情報の有用性はずっと高くなるでしょう。幸いなことに、iPhone SDK 3.0にはMap Kit APIが付属しており、これによってアプリケーション内にGoogleマップを簡単に表示できます。例を見てみましょう。
先ほど作成したプロジェクトを使って、LBSViewController.xibファイルのViewウィンドウにButtonビューを追加します(図3を参照)。
XcodeでFrameworksグループを右クリックし、MapKit.frameworkという新しいフレームワークを追加します。
次のコードの中で太字になっているステートメントをLBSViewController.hファイルに追加します。
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface LBSViewController : UIViewController
<CLLocationManagerDelegate> {
IBOutlet UITextField *accuracyTextField;
IBOutlet UITextField *latitudeTextField;
IBOutlet UITextField *longitudeTextField;
CLLocationManager *lm;
MKMapView *mapView;
}
@property (retain, nonatomic) UITextField *accuracyTextField;
@property (retain, nonatomic) UITextField *latitudeTextField;
@property (retain, nonatomic) UITextField *longitudeTextField;
-(IBAction) btnViewMap: (id) sender;
@end
Interface Builderに戻り、controlキーを押しながらButtonビューをクリックし、File's Ownerアイテムにドラッグし、btnViewMap:を選択します。
次のコードの中で太字になっているステートメントをLBSViewController.mファイルに追加します。
-(IBAction) btnViewMap: (id) sender {
[self.view addSubview:mapView];
}
- (void) viewDidLoad {
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
lm.distanceFilter = 1000.0f;
[lm startUpdatingLocation];
mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
mapView.mapType = MKMapTypeHybrid;
}
- (void) locationManager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation{
NSString *lat = [[NSString alloc] initWithFormat:@"%g",
newLocation.coordinate.latitude];
latitudeTextField.text = lat;
NSString *lng = [[NSString alloc] initWithFormat:@"%g",
newLocation.coordinate.longitude];
longitudeTextField.text = lng;
NSString *acc = [[NSString alloc] initWithFormat:@"%g",
newLocation.horizontalAccuracy];
accuracyTextField.text = acc;
[acc release];
[lat release];
[lng release];
MKCoordinateSpan span;
span.latitudeDelta=.005;
span.longitudeDelta=.005;
MKCoordinateRegion region;
region.center = newLocation.coordinate;
region.span=span;
[mapView setRegion:region animated:TRUE];
}
- (void) dealloc{
[mapView release];
[lm release];
[latitudeTextField release];
[longitudeTextField release];
[accuracyTextField release];
[super dealloc];
}
上記のコードでは基本的に次のことを行っています。
- ビューのロード時にMKMapViewクラスのインスタンスを作成し、表示するマップタイプ(ハイブリッド: この例では地図と衛星写真)を設定する。
- ユーザーがView Mapボタンを押したときに現在のビューに
mapViewオブジェクトを追加する。 - 位置情報が更新されたときに
mapViewオブジェクトのsetRegion:メソッドを使って位置を拡大する。
Command-rを押して、iPhoneシミュレータでアプリケーションをテストします。今度は、View Mapボタンを押すと、ロケーションマネージャで報告された位置が含まれている地図が表示されます(図4を参照)。
シミュレータは常に固定の位置を返すので、実際の機器をテストせずに済ませられるのはここまでです。実機テストを行えば、機器を持って移動するとそれに伴って地図が動的に更新される様子を確認できます。テストの際は、distanceFilterプロパティの値を小さくして、わずかな距離の変化も検知されるようにしてください。
ご覧いただいたように、iPhone SDKのCore Locationフレームワークを使用すると、位置情報を利用するサービスを簡単に実装できます。さらに、iPhone 3.0 SDKに含まれているMapKitを使用すると、マップ表示も簡単に実装できます。まだ位置情報を利用するアプリケーションを作成したことがなければ、これらの新機能を全部使って挑戦してみてください。


