Map View

Map View很常在尋找定位或是路線導覽中看到,接著簡單示範Map View的操作。
該範例使用Segmented Contrl來切換Map View的樣式,並且定位出目前的所在位址(如下第三張圖)。

**Step 1.**建立Single View專案,專案名稱為Map View

**Step 2.**編輯MainStoryboard.storyboard

加入:

  1. Toolbar
  2. Segmented Control
  3. Bar Button Item
  4. Flexible Space Bar Button Item
  5. Map View

**Step 3.**加入MapKit的framework

在檔案瀏覽的地方點選專案,接著畫面中間選擇TARGETS在往右邊上方找到Build Phases,下方可看到Link Binary With Libraries,點選下方的+加號,將MapKit.framework加進來。加入成功以後在你的專案資料夾內即可看到一個MapKit.framework

**Step 4.**編輯ViewController.h

  1. 引入MapKit/MapKit.h
  2. 定義變數,如同程式碼所述
  3. 定義兩個IBAction,該用途如程式碼的註解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController
{
MKMapView *mapView_;
UISegmentedControl *segmented_;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmented;

-(IBAction)showLocation:(id)sender; //顯示定位
-(IBAction)changeMapType:(id)sender; //改變地圖的type
@end

**Step 5.**編輯ViewController.m

一樣要先補上synthesize,接著是撰寫showLocation:,該方法很簡單,只要定義mapViewshowsUserLocation為YES即可顯示目前該使用者的位址。

1
2
3
4
5
6
@synthesize mapView = mapView_, segmented = segmented_;

-(IBAction)showLocation:(id)sender
{
self.mapView.showsUserLocation = YES;
}

在改變地圖的模式,使用Segmented Control,操作的方式如同Segmented Control,唯一不同的是在case內執行的東西;在case內去改變mapViewmapType,地圖模式一共有三種模式可以更換,因此您可以依自己的需求去做變換。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-(IBAction)changeMapType:(id)sender
{
NSInteger segmentedNum;
segmentedNum = self.segmented.selectedSegmentIndex;
switch (segmentedNum) {
case 0:
self.mapView.mapType = MKMapTypeStandard;
break;
case 1:
self.mapView.mapType = MKMapTypeSatellite;
break;
case 2:
self.mapView.mapType = MKMapTypeHybrid;
break;
default:
break;
}
}

**Step 6.**建立關連