 
 
這次要介紹如何使用 MapKit 來實做取得目前所在位置的經緯度,在 iOS 3.0 開始就有提供 MapKit 來讓開發者做地圖的相關應用,而這些功能的背後全都要仰賴 Google 數據庫所提供的資料,因此在使用時也必須要遵守 Google 地圖應用的服務條款,在此就不贅述,接下來我們就來實做這些功能。(View-based Template)
 首先先加入 MapKey 的 Framework,加入的方法是在 Groups & Files 內的專案名稱上按下右鍵 > Add > Existing Frameworks,之後選擇需要的 framework 並 Add 即可。  
#import @interface LocationViewController : UIViewController  { - (void)viewDidLoad {  [super viewDidLoad];  //建立MapView  map = [[MKMapView alloc] initWithFrame:CGRectMake(0.0f, 40.0f, 320.0f, 400.0f)]; 
 //顯示目前位置(藍色圓點)  map.showsUserLocation = YES; 
 //MapView的環境設置  map.mapType = MKMapTypeStandard;  map.scrollEnabled = YES;  map.zoomEnabled = YES; 
 //將MapView顯示於畫面  [self.view insertSubview:map atIndex:0]; 
 //取得目前MAP的中心點座標並show在對應的TextField中  double X = map.centerCoordinate.latitude;  double Y = map.centerCoordinate.longitude;  latitudeField.text = [NSString stringWithFormat:@"%6f", X];  longitudeField.text = [NSString stringWithFormat:@"%6f", Y]; }
//切換地圖為混合型態 map.mapType = MKMapTypeHybrid; 
 //切換地圖為標準型態 map.mapType = MKMapTypeStandard; 
 //切換地圖為衛星型態 map.mapType = MKMapTypeSatellite;
- (IBAction)onNowLocacion:(id)sender {  //取得現在位置  double X = map.userLocation.location.coordinate.latitude;  double Y = map.userLocation.location.coordinate.longitude; 
 //show在對應的TextField中  latitudeField.text = [NSString stringWithFormat:@"%6f", X];  longitudeField.text = [NSString stringWithFormat:@"%6f", Y]; 
 //自行定義的設定地圖函式  [self setMapRegionLongitude:Y andLatitude:X withLongitudeSpan:0.05 andLatitudeSpan:0.05]; } 
//自行定義的設定地圖函式 - (void)setMapRegionLongitude:(double)Y andLatitude:(double)X withLongitudeSpan:(double)SY andLatitudeSpan:(double)SX {  //設定經緯度  CLLocationCoordinate2D mapCenter;  mapCenter.latitude = X;  mapCenter.longitude = Y; 
 //Map Zoom設定  MKCoordinateSpan mapSpan;  mapSpan.latitudeDelta = SX;  mapSpan.longitudeDelta = SY; 
 //設定地圖顯示位置  MKCoordinateRegion mapRegion;  mapRegion.center = mapCenter;  mapRegion.span = mapSpan; 
 //前往顯示位置  [map setRegion:mapRegion];  [map regionThatFits:mapRegion]; } 透過自行定義的函式,我們也可以輸入想要的經緯度來移動地圖,不過如果只是單純想要取得目前的所在位置,可直接寫成這樣。  mapRegion.center = map.userLocation.location.coordinate; 
 
沒有留言:
張貼留言