Introduction
iOS maps help us locate positions, and iOS maps use the MapKit framework.
Example Steps
- Create a simple View-based application
- Select the project file, then choose the target, and add MapKit.framework.
- Add Corelocation.framework
- Add a map view to ViewController.xib and create an ibOutlet named mapView.
- Create a new file via "File-> New -> File... -> " select Objective C class, click Next
- Set "sub class of" as NSObject, name the class MapAnnotation
- Select Create
- Update MapAnnotation.h as shown below
#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
- Update MapAnnotation.m as shown below
#import "MapAnnotation.h"
@implementation MapAnnotation
-(id)initWithTitle:(NSString *)title andCoordinate: (CLLocationCoordinate2D)coordinate2d{
self.title = title;
self.coordinate =coordinate2d;
return self;
}
@end
- Update ViewController.h as shown below
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController<MKMapViewDelegate>
{
MKMapView *mapView;
}
@end
- Update ViewController.m as shown below
#import "ViewController.h"
#import "MapAnnotation.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
;
mapView = [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 = [ initWithTitle:@"Apple Head quaters" andCoordinate:location];
[mapView addAnnotation:newAnnotation];
CLLocationCoordinate2D location2;
location2.latitude = (double) 37.35239;
location2.longitude = (double) -122.025919;
MapAnnotation *newAnnotation2 = [ 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 = ;
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance (, 1500, 1500);
[mv setRegion:region animated:YES];
[mv selectAnnotation:mp animated:YES];
}
- (void)didReceiveMemoryWarning {
;
// Dispose of any resources that can be recreated.
}
@end
Output
When running the application, the output is as follows
When we scroll up the map, the output is as follows
YouTip