无涯教程-OC - 地图操作

170 阅读2分钟

地图对无涯教程找到位置始终很有帮助。使用MapKit框架将Map集成到iOS中。

涉及步骤

步骤1 - 创建一个基于视图的简单应用程序。

步骤2 - 选择您的项目文件,然后选择目标,然后添加MapKit.framework。

步骤3 - 无涯教程还应该添加Corelocation.framework。

步骤4 - 将MapView添加到ViewController.xib并创建一个ibOutlet并将其命名为mapView。

步骤5 - 选择"文件"→"新建"→"文件...",然后选择" Objective C class",然后单击"Next"。

步骤6 - 将类命名为MapAnnotation,将"sub class of"命名为NSObject。

步骤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;

//将注释添加到我们的地图视图 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]; }

//添加地图标注点时,缩放到它(1500范围) - (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

运行应用程序时,将得到如下所示的输出-

iOS Tutorial

当无涯教程向上滚动地图时,将得到如下所示的输出-

iOS Tutorial

参考链接

www.learnfk.com/ios/ios-acc…