5/06/2009

[iPhone程式]iPhone開發心得04-Mapkit之使用MKMapView實作Google Map

☉目標:使用內建的Mapkit Framework建立一個Google Map畫面,可以對地圖進行拖曳、放大、縮小。

☉限制:必須將iPhone的作業系統更新到OS 3.0版本,開發使用的SDK也要是SDK3.0才有內建Mapkit Framework


☉效果畫面:

2-1-a

☉步驟說明:

(1)建立一個新的Window-Based專案,將專案命名為LearnLoadMap
實際上我是繼續使用在iPhone開發心得03中所建立的專案。


(2)加入Mapkit Framework
在左方專案目錄的Framework資料夾上點選右鍵 Add->Existing Frameworks,選擇Mapkit.Framework

2-2-a



(3)接著我在專案中加入了ViewController,並命名為mapPageController
不知道怎麼加入和使用Library中的View Controller可以參考
[iPhone程式]iPhone開發心得03-在Window中加入一個UIViewController
現在MainWindow.xib的內容應該長的像這樣:
2-3-a

(4)在mapPageController.h中import mapkit.h,mapkit.h包含了所有關於map會使用到的類別,並且宣告一個MKMapView,我們會在mapPageController.m中使用到。最重要的一點是宣告<mkmapviewdelegate>,表示mapPageController可以指定成MKMapView的委派
#import <uikit uikit.h>
#import <mapkit/mapkit.h>


@interface mapPageController : UIViewController <mkmapviewdelegate> {
MKMapView *map1;
}

@property (nonatomic,retain) IBOutlet MKMapView *map1;

@end

(5)在mapPageController.m
用synthesize指示詞設定map1變數為public
@synthesize map1;

在viewDidLoad方法中撰寫載入地圖。
- (void)viewDidLoad {
[super viewDidLoad];

// Override point for customization after app launch
CGRect rect = CGRectMake(0, 0, 320, 460);
map1 = [[MKMapView alloc] initWithFrame:rect];
[map1 setDelegate: self];
[map1 setMapType: MKMapTypeStandard];


MKCoordinateRegion theRegion;

//set region center
CLLocationCoordinate2D theCenter;
theCenter.latitude =25.032054;
theCenter.longitude = 121.529266;
theRegion.center=theCenter;

//set zoom level
MKCoordinateSpan theSpan;
theSpan.latitudeDelta = 0.009;
theSpan.longitudeDelta = 0.009;
theRegion.span = theSpan;

//set scroll and zoom action
map1.scrollEnabled = YES;
map1.zoomEnabled = YES;

//set map Region
[map1 setRegion:theRegion];
[map1 regionThatFits:theRegion];

[self.view addSubview:map1];

}
MKCoordinateRegion表示座標區域(地圖上的某個區域),其中包含兩個重要的屬性,Center和Span。Center表示這塊區域的中心位置。Span表示這塊區域由中心往外延伸的距離(也就是Zoon Level)。

當地圖由中心往外延伸的距離小,那麼螢幕上地圖要顯示的區域就會比較小塊,地圖看起來就會比較大。

當MKMapView準備完成後,我們要將它顯示在畫面上,因此最後一行可以看到我將map加入self.view中。

0 意見:

張貼意見