地图与定位之大头针视图

该博文在上一博文地图与定位之地图、大头针的基础上完成。

在MyAnnotation.h 中增加属性

#import <Foundation/Foundation.h>

#import <MapKit/MapKit.h>

//MKAnnotation是一个协议 ,添加大头针久需要实现该协议

//coordinate 属性是必须的,所以需要实现该属性

@interface MyAnnotation : NSObject<MKAnnotation>

@property(nonatomic,strong)UIImage *image;

-(id)initWithCoordinate:(CLLocationCoordinate2D)coordinate title:(NSString *)title subtitle:(NSString *)subtitle;

@end

 在ViewController.m中

//

//  ViewController.m

//  MapView

//

//  Created by City--Online on 15/4/17.

//  Copyright (c) 2015年 CYW. All rights reserved.

//



#import "ViewController.h"

#import <CoreLocation/CoreLocation.h>

#import <MapKit/MapKit.h>

#import "MyAnnotation.h"

@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>

@property(nonatomic,strong)MKMapView *mapView;

@property(nonatomic,strong)CLLocationManager *locationManager;

@end



@implementation ViewController



- (void)viewDidLoad {

    [super viewDidLoad];

    _locationManager=[[CLLocationManager alloc]init];

    BOOL enable=[CLLocationManager locationServicesEnabled];

    NSLog(@"%d",[CLLocationManager authorizationStatus]);

    if (!enable) {

        NSLog(@"用户未开启定位服务,无法定位");

        return;

    }

    else if ([CLLocationManager authorizationStatus]<3)

    {

        [_locationManager requestWhenInUseAuthorization];

    }

    CLLocationDistance distance=10.0;

    _locationManager.distanceFilter=distance;

    _locationManager.delegate=self;

    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;

    [_locationManager startUpdatingLocation];

    self.mapView=[[MKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    

    //地图类型

//    typedef NS_ENUM(NSUInteger, MKMapType) {

//        MKMapTypeStandard = 0, //标准地图

//        MKMapTypeSatellite,   //卫星地图

//        MKMapTypeHybrid       //混合地图

//    }

    self.mapView.mapType=MKMapTypeStandard;

    //是否定位当前位置 否显示当前位置

    self.mapView.showsUserLocation=YES;

     //代理设置

    self.mapView.delegate=self;

    

//    typedef struct {

//        CLLocationCoordinate2D center;

//        MKCoordinateSpan span;

//    } MKCoordinateRegion;

    

    //中心点经纬度

    CLLocationCoordinate2D  locationCoordinate2D;

    locationCoordinate2D.latitude=22.544349;

    locationCoordinate2D.longitude= 113.94787;

    //范围比例尺

    MKCoordinateSpan coordinateSpan;

    //纬度

    coordinateSpan.latitudeDelta=0.05;

    //经度

    coordinateSpan.longitudeDelta=0.05;

    //设置显示区域

    MKCoordinateRegion coordinateRegion;

    coordinateRegion.center=locationCoordinate2D;

    coordinateRegion.span=coordinateSpan;

    [self.mapView setRegion:coordinateRegion animated:YES];

//    self.mapView.region=coordinateRegion;

    

//    typedef NS_ENUM(NSInteger, MKUserTrackingMode) {

//        MKUserTrackingModeNone = 0, // the user's location is not followed

//        MKUserTrackingModeFollow, // the map follows the user's location

//        MKUserTrackingModeFollowWithHeading, // the map follows the user's location and heading

//    }

    self.mapView.userTrackingMode=MKUserTrackingModeFollow;

    [self.view addSubview:self.mapView];

    

    UISegmentedControl *segmentedControl=[[UISegmentedControl alloc]initWithItems:@[@"普通地图",@"卫星地图",@"混合地图"]];

    segmentedControl.selectedSegmentIndex=0;

    [segmentedControl addTarget:self action:@selector(selectSegmentIndex:) forControlEvents:UIControlEventValueChanged];

    self.navigationItem.titleView=segmentedControl;



    //定义大头针类

    MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:locationCoordinate2D title:@"主标题" subtitle:@"子标题"];

    annotation.image=[UIImage imageNamed:@"map.png"];

    [self.mapView addAnnotation:annotation];

    

    //定义长按手势

    UILongPressGestureRecognizer *longPressGestureRecognizer=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(LongTap:)];

    [self.mapView addGestureRecognizer:longPressGestureRecognizer];

    

   

}

-(void)LongTap:(UILongPressGestureRecognizer *)gestureRecongizer

{

    if (gestureRecongizer.state==UIGestureRecognizerStateBegan) {

        NSLog(@"开始长按");

        //获取mapview手指点击位置

        CGPoint point=[gestureRecongizer locationInView:self.mapView];

        //转化为经纬度

        CLLocationCoordinate2D coordinate2D=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];

        //把当前位置转为地理位置

        CLGeocoder *geocoder=[[CLGeocoder alloc]init];

        CLLocation *location=[[CLLocation alloc]initWithLatitude:coordinate2D.latitude longitude:coordinate2D.longitude];

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

            if (error) {

                NSLog(@"失败:%@",error);

                return ;

            }

            if (placemarks.count>0) {

                CLPlacemark *placemark=[placemarks firstObject];

                

                MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:coordinate2D title:placemark.name subtitle:placemark.thoroughfare];

                annotation.image=[UIImage imageNamed:@"map.png"];

                NSLog(@"城市:%@",placemark.locality);

                NSLog(@"区:%@",placemark.subLocality);

                NSLog(@"省份:%@",placemark.administrativeArea);

                [self.mapView addAnnotation:annotation];

            }

        }];

        

        

        

    }

    else if(gestureRecongizer.state==UIGestureRecognizerStateChanged)

    {

        NSLog(@"长按移动");

    }

    else if(gestureRecongizer.state==UIGestureRecognizerStateEnded)

    {

         NSLog(@"长按结束");

    }

        

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{

    if (locations.count>0) {

        CLLocation *location=[locations firstObject];

        CLLocationCoordinate2D locationCoordinate2D =location.coordinate;

        [self.mapView setRegion:MKCoordinateRegionMake(locationCoordinate2D, self.mapView.region.span) animated:YES];

       

        NSLog(@"%lf ,%lf",locationCoordinate2D.longitude,locationCoordinate2D.longitude);

        

        MyAnnotation *annotation=[[MyAnnotation alloc]initWithCoordinate:locationCoordinate2D title:@"定位位置" subtitle:@"子标题"];

        annotation.image=[UIImage imageNamed:@"map.png"];

        [self.mapView addAnnotation:annotation];

       

    }

}



-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation

{

     //由于当前位置的标注也是一个大头针,所以此时需要判断,此代理方法返回nil使用默认大头针视图

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

        static NSString *key=@"annotation";

        MKAnnotationView *annotationView=[self.mapView dequeueReusableAnnotationViewWithIdentifier:key];

        if (annotationView==nil) {

            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key];

            //允许交互点击

            annotationView.canShowCallout=true;

            //定义详情视图偏移量

            annotationView.calloutOffset=CGPointMake(0, 1);

            //详情左视图

            UIImageView *imgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"email.png"]];

            imgView.frame=CGRectMake(20, 20, 40, 40);

            annotationView.leftCalloutAccessoryView=imgView;

            UIButton *btn=[UIButton buttonWithType:UIButtonTypeInfoDark];

            btn.frame=CGRectMake(20, 20, 40, 40);

            annotationView.rightCalloutAccessoryView=btn;



        }

        //修改大头针视图

        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的,位置是放到缓存池时的位置)

        annotationView.annotation=annotation;

//        //设置大头针图片

        annotationView.image=((MyAnnotation *)annotation).image;

        return annotationView;

    }

    else

    {

        return nil;

    }

}





//大头针选中

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

{

    MyAnnotation *annotation=view.annotation;

    NSLog(@"%@",annotation.title);

}

//定位失败

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

{

    NSLog(@"定位失败");

    NSLog(@"%@",error);

}

- (void)selectSegmentIndex:(UISegmentedControl *)control

{

    NSInteger index = control.selectedSegmentIndex;

    

    /*

     MKMapTypeStandard  普通地图(标准地图),

     MKMapTypeSatellite 卫星地图,

     MKMapTypeHybrid    混合地图

     */

    

    MKMapType mapType;

    

    switch (index)

    {

            //普通地图

        case 0:

            mapType = MKMapTypeStandard;

            break;

            //卫星地图

        case 1:

            mapType = MKMapTypeSatellite;

            break;

            //普通和卫星的混合地图

        case 2:

            mapType = MKMapTypeHybrid;

            break;

            

        default:

            break;

    }

    

    //改变地图类型

    self.mapView.mapType = mapType;

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



@end

 地图与定位之大头针视图

 

你可能感兴趣的:(视图)