iOS - 访问地图



地图对我们来说始终有助于找到地方。地图使用 MapKit 框架集成到 iOS 中。

涉及的步骤

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

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

步骤 3 - 我们还应该添加 Corelocation.framework。

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

步骤 5 - 通过选择文件 → 新建 → 文件... → 选择 Objective C 类,再单击下一步,创建一个新文件。

步骤 6 - 将类命名为 MapAnnotation,并将“子类”设置为 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;
   
   // 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

输出

当运行应用程序时,我们将获得如下所示的输出 −

iOS Tutorial

当向上滚动地图时,我们将获得如下所示的输出 −

iOS Tutorial
广告