[iPhone] 透過三軸感應縮放地圖
這次的作業三是希望透過iPhone上的三軸加速來縮放地圖
助教的投影片也說的很有趣:
情境: 大雨天, 右手拿傘, 背著大行李, 左手提著禮物(約重1公斤) 準備拜訪朋友. 但你迷路了!! 街頭的治安不太好, 於是用拿著袋子的左手拿出了iPhone使用Google Map... (zoom in/zoom out!!) 問題: 請設計一個操作方法, 使得可以單手操作iPhone Map功能, 而不用動用到拿傘的右手 or 讓“你”覺得有更好的操作體驗. [P.S]只要能單手操作DEMO,就拿到Bonus20%(手很大,手指很 長的操作方法除外!!)
加入座標點的範例:Link
詢問是否要啟用定位系統:Link
偵測Shake:Link
過濾重複的震動:Link
透過ZoomLevel做放大縮小:Link
基本上透過上面那幾個網址裡面的code湊一湊就做完這次作業了XD
我的Code
1. 新增Window-Bases application
2. 新增一個UIViewController叫做MapViewController.h
#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> #define kUpdateFrequency 30 //Hz typedef enum { NON, X_POS, X_NEG, Y_POS, Y_NEG, Z_POS, Z_NEG } ShakeType; @interface MapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate, UIAccelerometerDelegate> { IBOutlet MKMapView* mapView; CLLocationCoordinate2D theCenter; MKCoordinateSpan theSpan; NSInteger m_zoomLevel; } @property (nonatomic, retain) IBOutlet MKMapView* mapView; - (IBAction)zoomIn:(id)sender; - (IBAction)zoomOut:(id)sender; - (void)acceleratedInX:(float)xx Y:(float)yy Z:(float)zz; - (void)accelerometer: (UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration; - (void)zoom:(ShakeType)shakeType; - (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated; @end
3. 打開MapViewController,把MapView拉進去,然後hook到MapViewController.h裡面的mapView
4. 在MapViewController.m裡面啟動MapView以及CLLocationManager(開啟定位系統)
- (void)viewDidLoad { [super viewDidLoad]; [mapView setDelegate:self]; [mapView setMapType:MKMapTypeStandard]; // Set the coordinate of Taipei City MKCoordinateRegion theRegion; theCenter.latitude = 25.0320; theCenter.longitude = 121.5292; theRegion.center = theCenter; // Set the zoom level theSpan.latitudeDelta = 0.1; theSpan.longitudeDelta = 0.1; theRegion.span = theSpan; mapView.scrollEnabled = YES; mapView.zoomEnabled = YES; [mapView setRegion:theRegion]; [mapView regionThatFits:theRegion]; [self.view addSubview:mapView]; // Start the GPS system CLLocationManager *locationManager = [[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy= kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; // Setup the update frqeuency [[UIAccelerometer sharedAccelerometer] setUpdateInterval: (1.0 / kUpdateFrequency)]; [[UIAccelerometer sharedAccelerometer] setDelegate: self]; }
5. 系統自動取得目前座標後,更新地圖
//locationManager delegate - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ theCenter = newLocation.coordinate; m_zoomLevel = 17; [self setCenterCoordinate:theCenter zoomLevel:m_zoomLevel animated:NO]; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { }
之後就是加上上面那篇ZoomIn/ZoomOut的code
然後根據ShakeType(透過三軸加速器的值自己做設定)
對應到相對的動作
就可以透過三軸加速器縮放地圖了~