文档章节

[IOS地图开发系类]5、改变大头针MKPinAnnotationView的颜色

辉兔狼
 辉兔狼
发布于 2013/07/28 22:58
字数 888
阅读 1514
收藏 2

 在第四步的基础上,我们试着改变下大头针的颜色

//
//  MKPinAnnotationView.h
//  MapKit
//
//  Copyright (c) 2009-2012, Apple Inc. All rights reserved.
//

#import <MapKit/MKAnnotationView.h>

enum {
    MKPinAnnotationColorRed = 0,
    MKPinAnnotationColorGreen,
    MKPinAnnotationColorPurple
};
typedef NSUInteger MKPinAnnotationColor;

@class MKPinAnnotationViewInternal;

MK_CLASS_AVAILABLE(NA, 3_0)
@interface MKPinAnnotationView : MKAnnotationView
{
@private
    MKPinAnnotationViewInternal *_pinInternal;
}

@property (nonatomic) MKPinAnnotationColor pinColor;

@property (nonatomic) BOOL animatesDrop;

@end

从大头针的头文件中可以看到,它有一个颜色属性我们可以直接使用。

修改下CustomAnnotation.h和其实现文件,代码如下:

//
//  CustomAnnotation.h
//  LBS_002_mapview
//
//  Created by liqun on 13-7-25.
//  Copyright (c) 2013年 Block Cheng. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

#define PIN_RED @"Red"
#define PIN_GREEN @"Green"
#define PIN_PURPLE @"Purple"
@interface CustomAnnotation : NSObject<MKAnnotation>

@property (nonatomic, assign, readonly)     CLLocationCoordinate2D coordinate;
@property (nonatomic, copy, readonly)       NSString *title;
@property (nonatomic, copy, readonly)       NSString *subtitle;
@property (nonatomic, unsafe_unretained) MKPinAnnotationColor pinColor;
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates
                     title:(NSString *)paramTitle
                  subTitle:(NSString *)paramSubTitle;

+ (NSString *) reusableIdentifierforPinColor :(MKPinAnnotationColor)paramColor;
@end
//
//  CustomAnnotation.m
//  LBS_002_mapview
//
//  Created by liqun on 13-7-25.
//  Copyright (c) 2013年 Block Cheng. All rights reserved.
//

#import "CustomAnnotation.h"

@implementation CustomAnnotation

- (void)dealloc
{
    
    [_subtitle  release];
    [_title  release];
    
    [super dealloc];
}
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates
                     title:(NSString *)paramTitle
                  subTitle:(NSString *)paramSubTitle
{

    if (self = [super init]) {
        _coordinate = paramCoordinates;
        _title = [paramTitle copy];
        _subtitle = [paramSubTitle copy];
    }

    return self;
}


+ (NSString *) reusableIdentifierforPinColor :(MKPinAnnotationColor)paramColor{ NSString *result = nil;
    switch (paramColor){
        case MKPinAnnotationColorRed:{
            result = PIN_RED;
            break;
        }
        case MKPinAnnotationColorGreen:{
            result = PIN_GREEN;
            break;
        }
        case MKPinAnnotationColorPurple:{
            result = PIN_PURPLE;
            break;
        }
    }
    return result;
}
@end
最后,在ViewControlelr实现文件中,加上该注解类的颜色属性:

//
//  ViewController.m
//  LBS_002_mapview
//
//  Created by liqun on 13-7-25.
//  Copyright (c) 2013年 Block Cheng. All rights reserved.
//

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "CustomAnnotation.h"

@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
@property (nonatomic,retain)MKMapView* mapView;
@property (nonatomic,retain)CLLocationManager* locationManager;
@property (nonatomic,retain)CLLocation* location;
@property (nonatomic, retain) CLGeocoder *myGeocoder;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    MKMapView* map = [[MKMapView alloc] initWithFrame:self.view.frame];
    map.mapType = MKMapTypeStandard;
    map.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:map];
    [map release];
    self.mapView = map;
    self.mapView.delegate = self;
    
    UIButton *addBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    addBt.frame = CGRectMake(0, 00, 320, 50);
    [addBt setTitle:@"locationMe" forState:UIControlStateNormal];
   
    [ addBt addTarget:self action:@selector(handleLocationMe:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: addBt];
    
    if ([CLLocationManager locationServicesEnabled]){
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.purpose =
        @"To provide functionality based on user's current location.";
        [self.locationManager startUpdatingLocation];
    } else {
        /* Location services are not enabled.
         Take appropriate action: for instance, prompt the user to enable location services */
        NSLog(@"Location services are not enabled");
    }
    
    self.myGeocoder = [[CLGeocoder alloc] init];
    
}



- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *result = nil;
    if ([annotation isKindOfClass:[CustomAnnotation class]] == NO){
        return result;
    }
    if ([mapView isEqual:self.mapView] == NO){
        /* We want to process this event only for the Map View
         that we have created previously */
        return result;
    }
    /* First, typecast the annotation for which the Map View has
     fired this delegate message */
    CustomAnnotation *senderAnnotation = (CustomAnnotation *)annotation;
    /* Using the class method we have defined in our custom
     annotation class, we will attempt to get a reusable
     identifier for the pin we are about
     to create */
    NSString *pinReusableIdentifier =
    [CustomAnnotation reusableIdentifierforPinColor:senderAnnotation.pinColor];
    /* Using the identifier we retrieved above, we will
     attempt to reuse a pin in the sender Map View */
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:pinReusableIdentifier];
    if (annotationView == nil){
        /* If we fail to reuse a pin, then we will create one */
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:senderAnnotation reuseIdentifier:pinReusableIdentifier];
        /* Make sure we can see the callouts on top of
         each pin in case we have assigned title and/or
         subtitle to each pin */
        [annotationView setCanShowCallout:YES];
        annotationView.draggable = YES;
        annotationView.enabled = YES;
        
    }
    /* Now make sure, whether we have reused a pin or created a new one,
     
     that the color of the pin matches the color of the annotation */
    annotationView.pinColor = senderAnnotation.pinColor;
    //自定义图片时,不能用drop
    annotationView.animatesDrop = YES;
    result = annotationView;
    return result;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)handleLocationMe:(id)sender
{
    [self.myGeocoder
     reverseGeocodeLocation:self.location completionHandler:^(NSArray *placemarks, NSError *error) {
         if (error == nil &&[placemarks count] > 0){
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        /* We received the results */
        NSLog(@"Country = %@", placemark.country);
        NSLog(@"Postal Code = %@", placemark.postalCode);
        NSLog(@"Locality = %@", placemark.locality);
             NSLog(@"dic = %@", placemark.addressDictionary );
        NSLog(@"dic FormattedAddressLines= %@", [placemark.addressDictionary objectForKey:@"FormattedAddressLines"]);
             NSLog(@"dic Name = %@", [placemark.addressDictionary objectForKey:@"Name"]);
             NSLog(@"dic State = %@", [placemark.addressDictionary objectForKey:@"State"]);
             NSLog(@"dic Street = %@", [placemark.addressDictionary objectForKey:@"Street"]);
             NSLog(@"dic SubLocality= %@", [placemark.addressDictionary objectForKey:@"SubLocality"]);
             NSLog(@"dic SubThoroughfare= %@", [placemark.addressDictionary objectForKey:@"SubThoroughfare"]);
             NSLog(@"dic Thoroughfare = %@", [placemark.addressDictionary objectForKey:@"Thoroughfare"]);
        CLLocationCoordinate2D location =
        CLLocationCoordinate2DMake(self.location.coordinate.latitude, self.location.coordinate.longitude);
        /* Create the annotation using the location */
        
        CustomAnnotation *annotation =[[CustomAnnotation alloc] initWithCoordinates:location title:placemark.name subTitle:placemark.thoroughfare];
        /* And eventually add it to the map */
        annotation.pinColor = MKPinAnnotationColorPurple;
        [self.mapView addAnnotation:annotation];
        [annotation release];
        
        
    }
     else if (error == nil &&
              [placemarks count] == 0){
         NSLog(@"No results were returned.");
     }
     else if (error != nil){
         NSLog(@"An error occurred = %@", error);
     }
     }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    /* We received the new location */
    NSLog(@"Latitude = %f", newLocation.coordinate.latitude);
    NSLog(@"Longitude = %f", newLocation.coordinate.longitude);
    self.location = newLocation;
    
    
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    /* Failed to receive user's location */
}


- (void)dealloc
{
    self.mapView = nil;
    self.location = nil;
    self.locationManager = nil;
    
    [super dealloc];
}

@end
运行后,效果如下:

© 著作权归作者所有

共有 人打赏支持
辉兔狼

辉兔狼

粉丝 29
博文 52
码字总数 35345
作品 1
海淀
高级程序员
iOS原生地图开发指南续——大头针与自定义标注

iOS原生地图开发指南续——大头针与自定义标注 在上一篇博客中http://my.oschina.net/u/2340880/blog/415360系统总结了iOS原生地图框架MapKit中主体地图的设置与应用。这篇是上一篇的一个后续...

珲少
2015/05/15
0
2
iOS原生地图开发指南再续——地图覆盖物的应用

iOS原生地图开发指南再续——地图覆盖物的应用 一、引言 在前两篇博客中,将iOS系统的地图框架MapKit中地图的设置与应用以及关于添加大头针和自定义大头针的相关操作做了详细的介绍。链接如下...

珲少
2015/05/16
0
1
iphone开发 ---- GPS

11.1 iOS定位服务 11.2 iOS地图 11.3 Web地图 来自:http://www.itboat.net/thread-55296-1-1.html 11.1 iOS定位服务 iOS中有三个定位服务组件: Wifi定位,通过查询一个Wifi路由器的地理位置...

fcsong000833
2013/02/11
0
2
iOS原生地图开发进阶——使用导航和附近兴趣点检索

iOS原生地图开发进阶——使用导航和附近兴趣点检索 iOS中的mapKit框架对国际化的支持非常出色。在前些篇博客中,对这个地图框架的基础用法和标注与覆盖物的添加进行了详细的介绍,这篇博客将...

珲少
2015/05/18
0
0
iOS 定位和地图

一、定位 1.1 定位概要 要实现地图、导航功能,往往需要先熟悉定位功能,在iOS中通过Core Location框架进行定位操作。Core Location自⾝可以单独使用,和地图开发框架MapKit完全是独立的,但是往...

从訫开始_倾深爱
2016/09/08
28
0

没有更多内容

加载失败,请刷新页面

加载更多

no such module 'pop'问题

在github上 clone 了一个 swift 项目,编译时提示"no such module 'POP'"错误,查了一下居然是因为podfile中指定的最低版本是iOS 11.0,大于我测试手机的iOS版本10.3.3,将Podfile中的最低版...

yoyoso
今天
1
0
redis 系列一 -- 简介及安装

1.简介 redis -- remote dictionary server 远程字典服务 使用 C 语言编写; 高性能的 key-value数据库; 内存数据库,支持数据持久化。 Redis 是一个开源(BSD许可)的,内存中的数据结构存...

imbiao
今天
3
0
nginx log记录请求响应时间

有时为了方便分析接口性能等,需要记录请求的时长,通过修改nginx的日志格式可以做到,如 添加一个新的log_format log_format timed_combined '$remote_addr - $remote_user [$time_local] "...

swingcoder
今天
4
0
Spring MVC之RequestMappingHandlerMapping匹配

对于RequestMappingHandlerMapping,使用Spring的同学基本都不会陌生,该类的作用有两个: 通过request查找对应的HandlerMethod,即当前request具体是由Controller中的哪个方法进行处理; 查...

爱宝贝丶
今天
5
0
Java Web--增删改查之二界面后台java代码(转载参考)

/** *  *//** * @author Administrator * */package dao; import java.sql.*;public class DBConn {/** * 链接数据库 * @return */  ...

小橙子的曼曼
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部