使用MapView须符合MKMapViewDelegate协议
建立单视图工程,再建一个新类,该类是自定义的大头针,.h文件如下:
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
@interface CustomAnnotation :NSObject<MKAnnotation>
{
CLLocationCoordinate2D coordinate_;
NSString *title_;
NSString *subtitle_;
}
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end
.m 文件如下
#import "CustomAnnotation.h"
@implementation CustomAnnotation
@synthesize coordinate =coordinate_;
@synthesize title = title_;
@synthesize subtitle =subtitle_;
-(void)dealloc
{
[ release];
[subtitle_ release];
[super dealloc];
}
@end
根视图.h文件:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "CustomAnnotation.h"
@interface QQViewController :UIViewController<MKMapViewDelegate>
@property (weak, nonatomic) IBOutletMKMapView *map;
@end
根视图.m文件#import "QQViewController.h"
@interface QQViewController ()
@end
@implementation QQViewController
- (void)viewDidLoad
{
[superviewDidLoad];
self.map.delegate =self;
//设置地图格式
self.map.mapType = MKMapTypeStandard;
CLLocationCoordinate2D loc =CLLocationCoordinate2DMake(32.0500,118.78333);
CLLocationDegrees lat = loc.latitude;
CLLocationDegrees lon = loc.longitude;
CLLocationCoordinate2D theCoordinate;
//地图中心
CLLocationCoordinate2D theCenter;
theCoordinate.latitude = lat;
theCoordinate.longitude = lon;
//设置地图坐标显示范围
MKCoordinateRegion theRegin;
theCenter.latitude = lat;
theCenter.longitude = lon;
theRegin.center = theCenter;
//地图缩放级别
MKCoordinateSpan theSpan;
theSpan.latitudeDelta =0.01;
theSpan.longitudeDelta =0.01;
theRegin.span = theSpan;
[self.mapsetRegion:theRegin];
[self.mapregionThatFits:theRegin];
//显示用户位置
self.map.showsUserLocation =YES;
//创建大头针
CustomAnnotation *nan = [[CustomAnnotationalloc]init];
//大头针标题
nan.title =@"增加的大头针";
NSString *locDesc = [NSStringstringWithFormat:@"纬度:%.1f经度:%.1f",lat,lon];
//标注的位置
nan.coordinate = loc;
//大头针副标题
nan.subtitle = locDesc;
[self.mapaddAnnotation:nan];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma ================MKMapViewDelegate===============================
//改变大头针图表的颜色或者图片
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKAnnotationView *newAnimation = [[MKAnnotationView alloc]initWithAnnotation:annotationreuseIdentifier:annotation.title];
newAnimation.canShowCallout =YES;
newAnimation.image = [UIImageimageNamed:@"location"];
return newAnimation;
}
运行结果: