地图总是有助于我们找到地点.使用MapKit框架在iOS中集成地图.
涉及的步骤
步骤1 : 创建一个简单的基于视图的应用程序.
第2步 : 选择你的项目文件,然后选择目标,然后添加MapKit.framework.
第3步 : 我们还应该添加Corelocation.framework.
第4步 : 将MapView添加到ViewController.xib并创建一个ibOutlet并将其命名为mapView.
步骤5 : 选择File&rarr创建一个新文件;新的 → 档案... → 选择Objective C class并单击next.
步骤6 : 将类命名为MapAnnotation,将"sub class of"命名为NSObject.
步骤7 : 选择创建.
步骤8 : 更新MapAnnotation.h如下 :
#import#import @interface MapAnnotation : NSObject @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#import #import @interface ViewController : UIViewController { 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]; idmp = [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
输出
当我们运行应用程序时,我们会得到如下所示的输出 :
当我们向上滚动地图,我们将得到如下所示的输出 :