iOS -自定义大头标

iOS 从6.0开始地图数据不再由谷歌驱动,而是改为自己的地图,当然在国内他的数据还是由高德地图提供。在iOS中进行地图开发主要有两种方式,一种是直接利用MapKit框架进行地图开发,利用这种方式可以对地图进行精准的控制,另一种方式是直接调用苹果官方自带的地图应用,主要用于一些简单的地图应用(如:进行导航覆盖物填充等),无法进行精确的控制。需要声明的是百度地图也是在MapKit框架的基础上进行开发的

/** 使用系统地图(高德地图)的步骤: 1.添加MapKit.framework、Corelocation.framework 2.导入头文件#import#import----.地理编码--- 除了提供位置跟踪功能之外,在定位服务中还包含CLGeocoder类用于处理地理编码和逆地理编码(又叫反地理编码)功能。 地理编码:根据指定的位置(通常是地名)确定地理坐标(经、纬度)。 逆地理编码:可以根据地理坐标(经、纬度)确定位置信息(街道、门牌等)。 CLGeocoder最主要的两个方法就是- (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler;和- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;,分别用于地理编码和逆地理编码。 1.导入头文件<CoreLocation/CoreLocation.h>2.如果地图的反向解析的地址是英文--则可以在设置中-更改系统语言即可

*/

---------------------------

#import@interface ZBCustomCalloutView : UIView

@property (nonatomic, strong)UILabel* textLabel;

@end

#import "ZBCustomCalloutView.h"

#define kArrorHeight 10

@implementation ZBCustomCalloutView

- (void)drawRect:(CGRect)rect

{

CGFloat width = rect.size.width;

CGFloat height = rect.size.height;

//圆半径

CGFloat radius = (self.frame.size.height-kArrorHeight)*0.5;

CGContextRef context = UIGraphicsGetCurrentContext();

//移动到初始点

CGContextMoveToPoint(context, radius, 0);

//绘制第一条线和第一个四分之一圆弧

CGContextAddLineToPoint(context, width-radius, 0);

CGContextAddArc(context, width-radius, radius, radius, -0.5*M_PI, 0.0, 0);

//绘制第二条线和第二个四分之一圆弧

CGContextAddLineToPoint(context, width, height-radius);

CGContextAddArc(context, width-radius, height-radius, radius, 0.0, 0.5*M_PI, 0);

//绘制第三条线和第三个四分之一圆弧

CGContextAddLineToPoint(context, radius, height);

CGContextAddArc(context, radius, height-radius, radius, 0.5*M_PI, M_PI, 0);

//绘制第四条线和第四个四分之一圆弧

CGContextAddLineToPoint(context, 0, radius);

CGContextAddArc(context, radius, radius, radius, M_PI, 1.5*M_PI, 0);

//闭合路径

CGContextClosePath(context);

//填充半透明黑色

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

CGContextDrawPath(context, kCGPathFill);

self.layer.shadowColor = [[UIColor grayColor]CGColor];

self.layer.shadowOpacity = 1.0;

self.layer.shadowOffset = CGSizeMake(0.0f, 2.0f);

}

@end

---------------------------

#import#import "ZBCustomCalloutView.h"

@interface ZBCustomAnnotationView : MKAnnotationView

@property(nonatomic,strong) ZBCustomCalloutView* calloutView;

@end

#import "ZBCustomAnnotationView.h"

#define kCalloutWidth 120.0

#define kCalloutHeight 45.0

@implementation ZBCustomAnnotationView

#pragma mark----一运行就触发

- (ZBCustomCalloutView *)calloutView{

if (!_calloutView) {

_calloutView = [[ZBCustomCalloutView alloc]initWithFrame:CGRectMake(0, 0, kCalloutWidth, kCalloutHeight)];

_calloutView.backgroundColor = [UIColor redColor];

_calloutView.center = CGPointMake(CGRectGetWidth(self.bounds)/2.0f+self.calloutOffset.x, -CGRectGetHeight(_calloutView.bounds)/2.0f+self.calloutOffset.y);

[self addSubview:_calloutView];

_calloutView.textLabel = [[UILabel alloc]init];

[_calloutView addSubview:_calloutView.textLabel];

_calloutView.textLabel.textColor = [UIColor blackColor];

_calloutView.textLabel.textAlignment = NSTextAlignmentCenter;

_calloutView.textLabel.font = [UIFont systemFontOfSize:18];

_calloutView.textLabel.frame = CGRectMake(0, 0, kCalloutWidth, kCalloutHeight);

}

return _calloutView;

}

#pragma mark-----当点击的时候会触发

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{

if (self.selected ==selected) {

return;

}

if (selected) {

if (self.calloutView == nil) {

//            self.calloutView = [[ZBCustomCalloutView alloc]initWithFrame:CGRectMake(0, 0, kCalloutWidth, kCalloutHeight)];

//            self.calloutView.backgroundColor = [UIColor whiteColor];

//            self.calloutView.center = CGPointMake(CGRectGetWidth(self.bounds)/2.0f+self.calloutOffset.x, -CGRectGetHeight(self.calloutView.bounds)/2.0f+self.calloutOffset.y);

//            [self addSubview:self.calloutView];

//

//            self.calloutView.textLabel = [[UILabel alloc]init];

//            [self.calloutView addSubview:self.calloutView.textLabel];

//            self.calloutView.textLabel.textColor = [UIColor blackColor];

//            self.calloutView.textLabel.textAlignment = NSTextAlignmentCenter;

//            self.calloutView.textLabel.font = [UIFont systemFontOfSize:18];

//            self.calloutView.textLabel.frame = CGRectMake(0, 0, kCalloutWidth, kCalloutHeight);

}

}else{

}

[super setSelected:selected animated:animated];

}

@end

---------------------------

-------需要添加地图的控制器-----

- (void)initMap{      

  //初始化大头针    [self initAnnotaiton]; 

 //初始化地图    [self setUpMapView];      

  //将大头针添加到地图上//    [_mapView1 addAnnotations:@[self.startAnnotation,self.endAnnotation]];    [_mapView1 addAnnotations:@[self.startAnnotation]];   

 //调用此方法直接显示出大头针气泡,调用此方法会执行大头针的点击代理    [_mapView1 selectAnnotation:self.startAnnotation animated:YES];    [_mapView1 selectAnnotation:self.endAnnotation animated:NO];   

 //地图移动,缩放    MKCoordinateRegion region;//表示范围的结构体    region.center = self.startAnnotation.coordinate;

//中心点    region.span.latitudeDelta = 0.1;

//经度范围(设置为0.1表示范围为0.2的经度范围) 

   region.span.longitudeDelta = 0.1;

//纬度范围    [_mapView1 setRegion:region animated:YES];        

//初始化地理编码    _geocoder = [[CLGeocoder alloc]init];}

#pragma mark----根据地名确定地理坐标- (void)getCoordinateFromAddress:(NSString *)address{       

 //地理编码    [_geocoder geocodeAddressString:address completionHandler:^(NSArray* _Nullable placemarks, NSError * _Nullable error) {               

 //取得第一个坐标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址       

 CLPlacemark* placemark = [placemarks firstObject];              

  CLLocation* location = placemark.location;//位置      

  CLRegion* region = placemark.region;//区域        

NSDictionary* addressDic = placemark.addressDictionary;//详细地址信息字典,包含以下部分信息               

 NSString* addressName = placemark.name;//地名        

NSString* addressThoroughfare = placemark.thoroughfare;//街道        

NSString* addSubThoroughfare = placemark.subThoroughfare;//街道相关信息,例如门牌等。                        

NSString* addressLocality = placemark.locality;//城市       

 NSString* addressSubLocality = placemark.subLocality;//城市相关信息,例如标志性建筑       

 NSString* addressAdministrativeArea = placemark.subAdministrativeArea;//其他行政区域信息        

NSString* addressPostalCode = placemark.postalCode;//邮编      

  NSString* addressIsOcountryCode = placemark.ISOcountryCode;//国家编码    

    NSString* addressInlandWater = placemark.inlandWater;//水源、湖泊       

 NSString* addressOcean = placemark.ocean;//海洋              

  NSArray* addressAreasOfInterest = placemark.areasOfInterest;//关联的或利益相关的地标               

 NSLog(@"位置:%@,区域:%@,详细信息:%@",location,region,addressDic);    }];}

#pragma mark---根据坐标取得地名

- (void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{      

  //反地理编码    CLLocation* location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];   

 [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray* _Nullable placemarks, NSError * _Nullable error) {             

   CLPlacemark* placemark = [placemarks firstObject];     

   NSLog(@"详细地址:%@",placemark.addressDictionary );    }];                

}

//初始化大头针- (void)initAnnotaiton{       

 _startAnnotation = [[MKPointAnnotation alloc]init];  

  _startAnnotation.coordinate = CLLocationCoordinate2DMake(39.90841537, 116.45969689); 

   _startAnnotation.title = @"国贸";    }

//初始化地图- (void)setUpMapView{  

  //    _mapView1 = [[MKMapView alloc]init];  

  _mapView1 = [MKMapView new];    

[self.view addSubview:_mapView1];  

  _mapView1.frame = [UIScreen mainScreen].bounds;    

_mapView1.delegate = self;  

  _mapView1.showsScale = NO;    _mapView1.showsCompass = NO; 

   UITapGestureRecognizer* tapGesRecon = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesRwcon:)];   

 [_mapView1 addGestureRecognizer:tapGesRecon];}

- (void)didTapGesRwcon:(UITapGestureRecognizer *)tap{   

 //移除所有标记    [self.mapView1 removeOverlays:self.mapView1.overlays];    [self.mapView1 removeAnnotations:self.mapView1.annotations];       

 //获取当前位置    CGPoint location = [tap locationInView:self.view];   

 //经纬度    CLLocationCoordinate2D coordinate = [self.mapView1 convertPoint:location toCoordinateFromView:self.mapView1];        

CLLocation* location123 = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];  

  [_geocoder reverseGeocodeLocation:location123 completionHandler:^(NSArray* _Nullable placemarks, NSError * _Nullable error) {                //创建新的标注        CLPlacemark* placemark = [placemarks firstObject];     

   MKPointAnnotation* annotation = [[MKPointAnnotation alloc]init];        CLLocationCoordinate2D cool;        

coor.latitude = coordinate.latitude;     

 coor.longitude = coordinate.longitude;      

  annotation.coordinate = cool;               

 //移动到当前定位位置      

  [self.mapView1 setCenterCoordinate:coordinate animated:YES];     

   [self.mapView1 viewForAnnotation: annotation];                

//添加标注        [self.mapView1 addAnnotation: annotation];              

  annotation.coordinate = coordinate;        

annotation.subtitle = [placemark.addressDictionary objectForKey:@"FormattedAddressLines"];                annotationView.calloutView.textLabel.text = placemark.locality;        

NSLog(@"详细地址:%@",placemark.addressDictionary);        

//关键字FormattedAddressLines-为详细地址    }];}

#pragma mark-----MKMapViewDelegate

//添加大头针代理

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation{

if ([annotation isKindOfClass:[MKPointAnnotation class]]) {

static NSString* resuedIndentifier = @"ZBMKAnnotationID";

annotationView = (ZBCustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:resuedIndentifier];

if (annotationView == nil) {

annotationView = [[ZBCustomAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:resuedIndentifier];

}

if (annotation == self.startAnnotation) {

UIImage* image = [UIImage imageNamed:@"icon_payment@2x"];

annotationView.image = image;

annotationView.centerOffset = CGPointMake(0, -0.5*image.size.height);

}

else{

UIImage* image = [UIImage imageNamed:@"icon_myColloction@2x"];

annotationView.image = image;

annotationView.centerOffset = CGPointMake(0, -0.5*image.size.height);

}

return annotationView;

}

return nil;

}

//大头针点击代理--点击大头针调用

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{

annotationView = (ZBCustomAnnotationView *)view;

annotationView.calloutView.textLabel.text = view.annotation.title;

}

- (void)dealloc{

#if DEBUG

static NSMutableArray* unusedObjects;

if (!unusedObjects) {

unusedObjects = [NSMutableArray new];

}

[unusedObjects addObject:_mapView1];

#endif

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容