IOS地圖開發
IOS地圖開發
簡介
IOS地圖幫助我們定位位置,IOS地圖使用 MapKit 框架。
實例步驟
1.建立一個簡單的View based application
2.選擇專案文件,然後選擇目標,然後新增MapKit.framework.
#3.新增Corelocation.framework
4.向ViewController.xib 新增地圖檢視和建立ibOutlet 並且命名為mapView。
5.透過"File-> New -> File... -> "選擇Objective C class建立一個新的文件,按下一步
6."sub class 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
#輸出
執行應用程式時,輸出結果如下
當我們向上捲動地圖時,輸出結果如下