您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 基礎知識 >> iOS 入門介紹

iOS 地圖開發教學:MapKit 與地圖標註

編輯:iOS 入門介紹

iOS 地圖開發


簡介

iOS 的地圖功能由 MapKit 框架提供,可顯示地圖、標註地點並取得座標資訊。

實作步驟

1. 建立一個簡單的 View-based Application。

2. 選擇專案檔,進入 Targets,加入 MapKit.framework。

3. 加入 CoreLocation.framework。

4. 在 ViewController.xib 中加入地圖視圖,並建立名為 mapView 的 IBOutlet。

5. 透過「File」→「New」→「File...」選擇 Objective-C class,點擊下一步。

6. 將 Subclass of 設為 NSObject,類別命名為 MapAnnotation。

7. 點擊建立。

8. 更新 MapAnnotation.h:

 #import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface MapAnnotation : NSObject<MKAnnotation> @property (nonatomic, strong) NSString *title; @property (nonatomic, readwrite) CLLocationCoordinate2D coordinate; - (id)initWithTitle:(NSString *)title andCoordinate: (CLLocationCoordinate2D)coordinate2d; @end 

9. 更新 MapAnnotation.m:

 #import "MapAnnotation.h" @implementation MapAnnotation -(id)initWithTitle:(NSString *)title andCoordinate: (CLLocationCoordinate2D)coordinate2d{ self.title = title; self.coordinate =coordinate2d; return self; } @end 

10. 更新 ViewController.h:

 #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController<MKMapViewDelegate> { MKMapView *mapView; } @end 

11. 更新 ViewController.m:

 #import "ViewController.h" #import "MapAnnotation.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; mapView = [[MKMapView alloc]initWithFrame: CGRectMake(10, 100, 300, 300)]; mapView.delegate = self; mapView.centerCoordinate = CLLocationCoordinate2DMake(37.32, -122.03); mapView.mapType = MKMapTypeHybrid; CLLocationCoordinate2D location; location.latitude = (double) 37.332768; location.longitude = (double) -122.030039; // Add the annotation to our map view MapAnnotation *newAnnotation = [[MapAnnotation alloc] initWithTitle:@"Apple Head quaters" andCoordinate:location]; [mapView addAnnotation:newAnnotation]; CLLocationCoordinate2D location2; location2.latitude = (double) 37.35239; location2.longitude = (double) -122.025919; MapAnnotation *newAnnotation2 = [[MapAnnotation alloc] initWithTitle:@"Test annotation" andCoordinate:location2]; [mapView addAnnotation:newAnnotation2]; [self.view addSubview:mapView]; } // When a map annotation point is added, zoom to it (1500 range) - (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views { MKAnnotationView *annotationView = [views objectAtIndex:0]; id <MKAnnotation> mp = [annotationView annotation]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance ([mp coordinate], 1500, 1500); [mv setRegion:region animated:YES]; [mv selectAnnotation:mp animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end 

輸出結果

執行程式時:

向上捲動地圖後:

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved