1天学习1个类库 UIMapView annomation 示例

mapview 的类库用到的比较多了.不仅仅是1个uimapview. 直接发代码:

CWPlaceAnnotationView.h

#import <MapKit/MapKit.h>

@interface CWPlace : NSObject<MKAnnotation> {
    NSString *_sTitle_;
    NSString *_sSubTitle_;
}

@property (nonatomic) CLLocationCoordinate2D locationCoordinate2d;

@end


@interface CWPlaceAnnotationView : MKAnnotationView

@end

CWPlaceAnnotationView.m 增加解析地址功能

#import "CWPlaceAnnotationView.h"

@implementation CWPlace

@synthesize locationCoordinate2d = _locationCoordinate2d;

- (void) dealloc {
    [_sTitle_ release];
    [_sSubTitle_ release];
    
    [super dealloc];
}

- (NSString *) title {
    return _sTitle_;
}
- (NSString *) subtitle {
    return _sSubTitle_;
}

- (void) setCoordinate:(CLLocationCoordinate2D)newCoordinate {
    _locationCoordinate2d = newCoordinate;
    
    CLLocation *local = [[CLLocation alloc] initWithLatitude:_locationCoordinate2d.latitude longitude:_locationCoordinate2d.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:local completionHandler:^(NSArray *placemarks, NSError *error){
//        NSLog(@"placemarks : %@",placemarks);
        CLPlacemark *placeMark = [placemarks objectAtIndex:0];
        if (_sTitle_) {
            [_sTitle_ release];
        }
        if (_sSubTitle_) {
            [_sSubTitle_ release];
        }
        _sTitle_ = [placeMark.locality copy];
        _sSubTitle_ = [placeMark.thoroughfare copy];
//        _sTitle_ = [[placemarks objectAtIndex:0] copy];
//        _sSubTitle_ = [[placemarks objectAtIndex:1] copy];
    }];
    [geocoder release];
    [local release];
}

- (CLLocationCoordinate2D) coordinate {
    return _locationCoordinate2d;
}

@end

@implementation CWPlaceAnnotationView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id) initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]) {
        self.frame = CGRectMake(0, 0, 100, 100);
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end



main.m(地图显示,标注功能,计算地图上2点之间的距离)

//
//  main.m
//  ControlDemo
//
//  Created by watsy0007 on 12-6-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "CWPlaceAnnotationView.h"
#import <CoreLocation/CoreLocation.h>

#define MAPVIEW_SEGMENTCONTROL_TAG_TYPE             1
#define MAPVIEW_SEGMENTCONTROL_TAG_USERTRACK        2

#pragma mark -
#pragma mark 控制器

@interface ViewController : UIViewController <MKMapViewDelegate> {
    UIView *_infoView_;
    UIView *_mapBackgroundView_;
    MKMapView   *_mapView_;
}

@end


@implementation ViewController

- (void) dealloc {
    [_infoView_ release];
    [_mapView_ release];
    [_mapBackgroundView_ release];
    
    [super dealloc];
}

- (void) segControlAction:(id) sender {
    UISegmentedControl *seg = (UISegmentedControl *) sender;
    if (seg.tag == MAPVIEW_SEGMENTCONTROL_TAG_TYPE) {
        switch (seg.selectedSegmentIndex) {
            case 0:
                _mapView_.mapType = MKMapTypeStandard;
                break;
                
            case 1:
                _mapView_.mapType = MKMapTypeSatellite;
                break;
                
            case 2:
                _mapView_.mapType = MKMapTypeHybrid;
                break;
            default:
                break;
        }
    } else if (seg.tag == MAPVIEW_SEGMENTCONTROL_TAG_USERTRACK) {
        switch (seg.selectedSegmentIndex) {
            case 0:
                _mapView_.userTrackingMode = MKUserTrackingModeNone;
                break;
                
            case 1:
                _mapView_.userTrackingMode = MKUserTrackingModeFollow;
                break;
                
            case 2:
                _mapView_.userTrackingMode = MKUserTrackingModeFollowWithHeading;
                break;
                
            default:
                break;
        }
    }
    
}
- (void) BarItemAction:(id) sender {
    BOOL bMap = ([_mapBackgroundView_ superview] == nil);

    
    [UIView transitionWithView:self.view 
                        duration:1.0 
                        options:bMap ? UIViewAnimationOptionTransitionFlipFromLeft :UIViewAnimationOptionTransitionFlipFromRight
                        animations:^(){
                            if (!bMap) {
                                [self.view addSubview:_infoView_];
                                [_mapBackgroundView_ removeFromSuperview];
                                
                            } else {
                                [self.view addSubview:_mapBackgroundView_];
                                [_infoView_ removeFromSuperview];
                            }
                        } 
                        completion:^(BOOL b){
                            
                        }];
}

- (NSArray *) createRightItems {

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [btn addTarget:self action:@selector(BarItemAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *infoItem = [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease];
    
    return [NSArray arrayWithObjects:infoItem, nil];
    
}

- (NSArray *) createLeftItems {
    MKUserTrackingBarButtonItem *item = [[[MKUserTrackingBarButtonItem alloc] initWithMapView:_mapView_] autorelease];
    
    return [NSArray arrayWithObjects:item, nil]; 
}

- (void) annoViewRightBtnClick:(id) sender {
    NSLog(@"显示更多操作");
}

//说明说地图设置
- (void) infoViewControl {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.frame = CGRectMake(0, 0, 320, 420);
    label.numberOfLines = 3;
    label.textAlignment = UITextAlignmentCenter;
    label.text = @"watsy0007\n QQ:258841679\n群:125807534";
    [_infoView_ addSubview:label];
    [label release];
    
    //显示类型
    UILabel *labMapType = [[UILabel alloc] initWithFrame:CGRectZero];
    labMapType.backgroundColor = [UIColor clearColor];
    labMapType.frame = CGRectMake(10, 30, 75, 35);
    labMapType.text = @"显示类型:";
    [_infoView_ addSubview:labMapType];
    [labMapType release];
    UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"标准",@"卫星",@"混合", nil]];
    segControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segControl.tag = MAPVIEW_SEGMENTCONTROL_TAG_TYPE;
    [segControl addTarget:self action:@selector(segControlAction:) forControlEvents:UIControlEventValueChanged];
    
    segControl.frame = CGRectMake(85, 30, 225, 35);
    [_infoView_ addSubview:segControl];
    [segControl release];
    
    //地图模式
    labMapType = [[UILabel alloc] initWithFrame:CGRectZero];
    labMapType.backgroundColor = [UIColor clearColor];
    labMapType.frame = CGRectMake(10, 70, 75, 35);
    labMapType.text = @"地图模式:";
    [_infoView_ addSubview:labMapType];
    [labMapType release];
    segControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"静态",@"跟随",@"图随路转", nil]];
    segControl.tag = MAPVIEW_SEGMENTCONTROL_TAG_USERTRACK;
    segControl.segmentedControlStyle = UISegmentedControlStyleBar;
    [segControl addTarget:self action:@selector(segControlAction:) forControlEvents:UIControlEventValueChanged];
    
    segControl.frame = CGRectMake(85, 70, 225, 35);
    [_infoView_ addSubview:segControl];
    [segControl release];
}

//随机生成1些标注位置
- (NSArray *) randomAnnotation:(NSInteger) nMax {
    random();
    
    NSMutableArray *annotationArray = [NSMutableArray array];
    for (int i = 0; i < nMax; i++) {
        CWPlace *place = [[CWPlace alloc] init];
        double dRandlatitude = (double)(rand() % 10000) / 1000000;
        double dRandlongitude  = (double)(rand() % 10000) / 1000000;
        BOOL bAdd = rand() % 2;
        if (bAdd) {
            dRandlatitude = -dRandlatitude;
        } 
        bAdd = rand() % 2;
        if (bAdd) {
            dRandlongitude = -dRandlongitude;
        } 
        
        [place setCoordinate:CLLocationCoordinate2DMake(22.551368 +  dRandlatitude, 113.882654 + dRandlongitude)];
        [annotationArray addObject:place];
        [place release];
    } 
    return annotationArray;
}

- (float) distanceToLPU:(CLLocationCoordinate2D ) userCoordinate
          calCoordinate:(CLLocationCoordinate2D) anoCoordinate {
    
    CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:userCoordinate.latitude longitude:userCoordinate.longitude];
    
    CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:anoCoordinate.latitude longitude:anoCoordinate.longitude];  
    
    float distanceMeters = [pointALocation distanceFromLocation:pointBLocation];  
    
    [pointALocation release];
    [pointBLocation release];  
    
    return distanceMeters;
}

- (void) mapViewControl {
    //地图
    _mapView_ = [[MKMapView alloc] initWithFrame:_mapBackgroundView_.bounds];
    _mapView_.delegate = self;
    //显示用户坐标
    _mapView_.showsUserLocation = YES;
    
    //设置地区
    MKCoordinateRegion currentRegion = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(22.551368,113.882654), 0.0002, 0.0002);
//    _mapView_.region = currentRegion;
    [_mapView_ setRegion:currentRegion animated:YES];
//    
//    _mapView_.centerCoordinate = currentRegion.center;
//    [_mapView_ setCenterCoordinate:currentRegion.center animated:YES];
//
    MKCoordinateRegion fitRegin = [_mapView_ regionThatFits:currentRegion];
    [_mapView_ setRegion:fitRegin animated:YES];
    
    [_mapView_ addAnnotations:[self randomAnnotation:10]];

    
    [_mapBackgroundView_ addSubview:_mapView_];
    
    
    [self.view addSubview:_mapBackgroundView_];
}


- (void) loadView {
    [super loadView];
//    NSLog(@"距离");
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"MapKit Demo";
    
    _infoView_ = [[UIView alloc] initWithFrame:self.view.bounds];
    [_infoView_ setBackgroundColor:[UIColor clearColor]];
    
    //地图背景
    _mapBackgroundView_ = [[UIView alloc] initWithFrame:self.view.bounds];
    [_mapBackgroundView_ setBackgroundColor:[UIColor clearColor]];
    
    [self infoViewControl];
    [self mapViewControl];
    
    self.navigationItem.rightBarButtonItems = [self createRightItems];
    self.navigationItem.leftBarButtonItems = [self createLeftItems];
}

- (void) viewWillUnload {
    
    [_infoView_ release];
    [_mapView_ release];
    [_mapBackgroundView_ release];
    
    [super viewWillUnload];
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}

- (void) viewDidLoad {
    [super viewDidLoad];
}

#pragma mark -
#pragma mark MKMapViewDelegate delegate

//返回地图标注视图
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    static NSString *sAnno = @"sAnnoString";
    CWPlaceAnnotationView *annoView = (CWPlaceAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:sAnno];
    
    if (annoView == nil) {
        if (annotation == mapView.userLocation) {
            annoView = [[[CWPlaceAnnotationView alloc] initWithAnnotation:annotation 
                                                          reuseIdentifier:sAnno] autorelease];
            
            annoView.image = [UIImage imageNamed:@"bullseye.png"]; 
        } else {
            annoView = [[[CWPlaceAnnotationView alloc] initWithAnnotation:annotation 
                                                     reuseIdentifier:sAnno] autorelease];
            
            annoView.image = [UIImage imageNamed:@"pin.png"]; 
        }
    }
    
    
    //点击显示
    annoView.canShowCallout = YES;
    
    return annoView;
}

//点击地图上的标注
- (void) mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    view.draggable = YES;
//    NSLog(@"didSelectAnnotationView");
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [btn addTarget:self action:@selector(annoViewRightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    view.leftCalloutAccessoryView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)] autorelease];
    view.rightCalloutAccessoryView = btn;
    view.draggable = YES;
    //
    [view setDragState:MKAnnotationViewDragStateStarting animated:YES];
}

//开始更新用户位置
- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView {
    
    NSLog(@"%@",@"mapViewWillStartLocatingUser");
}
//停止更新用户位置
- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView {
        NSLog(@"%@",@"mapViewDidStopLocatingUser");
}
//更新用户位置
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation  {
//        NSLog(@"%@",@"didUpdateUserLocation");
//    MKMapRect visiableRect = [_mapView_ visibleMapRect];
//    NSArray *annoArray = [_mapView_ annotations];
//    
//    MKMapPoint pUserPoint = MKMapPointForCoordinate(_mapView_.userLocation.coordinate);
//    
//    for (int i = 0; i < [annoArray count]; i++) {
//        CWPlace *place = [annoArray objectAtIndex:i];
//        //缩放位置,用于显示全部的坐标点
//        MKMapPoint pMapPoint = MKMapPointForCoordinate(place.coordinate);
//        
//        //计算与当前位置的距离
//        MKMapPoint pUserPoint = MKMapPointForCoordinate(_mapView_.userLocation.coordinate);
//        
//        NSLog(@"ccloation :%.2f\nmapPointDistance:%.2f\n\n",[self distanceToLPU:_mapView_.userLocation.location.coordinate calCoordinate:place.coordinate],MKMetersBetweenMapPoints(pUserPoint,pMapPoint));
//        
//        if (pMapPoint.x < visiableRect.origin.x) {
//            visiableRect.origin.x = pMapPoint.x;
//            visiableRect.size.width = visiableRect.size.width + (visiableRect.origin.x - pMapPoint.x);
//        } 
//        
//        if (pMapPoint.x  > (visiableRect.origin.x + visiableRect.size.width)) {
//            visiableRect.size.width = visiableRect.size.width + (pMapPoint.x - (visiableRect.origin.x + visiableRect.size.width));
//        } 
//        
//        if (pMapPoint.y < visiableRect.origin.y) {
//            visiableRect.origin.y = pMapPoint.y;
//            visiableRect.size.height = visiableRect.size.height + (visiableRect.origin.y - pMapPoint.y);
//        } 
//        
//        if (pMapPoint.y  > (visiableRect.origin.y + visiableRect.size.height)) {
//            visiableRect.size.height = visiableRect.size.height + (pMapPoint.y - (visiableRect.origin.y + visiableRect.size.height));
//        } 
//        
//    } 
//    [_mapView_ setVisibleMapRect:visiableRect animated:YES];
}

//允许修改地图标注以后 地图标注状态改变回调
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState 
   fromOldState:(MKAnnotationViewDragState)oldState {
    NSLog(@"didChangeDragState :new %d\told %d",newState,oldState);
}

//响应点击注解上的控件回调
- (void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    NSLog(@"%@",@"calloutAccessoryControlTapped");
}

@end


//-----------------------------------------------------------------------------------------------------

#pragma mark -
#pragma mark AppDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIViewController *viewController;

@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (void) dealloc {
    [_window release];
    [_viewController release];
    
    [super dealloc];
}

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    self.viewController = [[ViewController alloc] init];
    
    UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:self.viewController]; 
    self.window.rootViewController = controller;
    [controller release];
    
    [self.window makeKeyAndVisible];
    return YES;
}

@end

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值