//
//  GuideMapController.m
//  ArcGis
//
//  Created by Mac Book DQ02 on 16/3/16.
//  Copyright © 2016年 Xu Mengzhu. All rights reserved.
//

#import "GuideMapController.h"

#define degreesToRadians(x) (M_PI*x/180.0)
#define downloadUrl @"http://gwms.517gts.com/upload/create_scenic_area_info.zip"


@interface GuideMapController ()//<AGSRouteTaskDelegate>

@end

NSArray *myGraphicArr;

@implementation GuideMapController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor= [UIColor whiteColor];
    
    //设置导航栏
   [self setNavigationBar];
    
    self.searchResultModelArr = [[NSMutableArray alloc]initWithCapacity:10];
    self.searchResultGraphicArr=[[NSMutableArray alloc]initWithCapacity:10];
    
    //初始化底部工具条视图，用view＋button做
    _bottomView = [[BottomView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-49, self.view.frame.size.width, 49)];
    _bottomView.delegate = self;
    [self.view addSubview:_bottomView];

    
    //设置地图的视图
    [self initMapView];
    
    //设置定位，放大，缩小按钮
    _contentViewWidth = self.view.frame.size.width;
    _contentViewHeight = self.view.frame.size.height - self.navigationController.navigationBar.frame.size.height-self.bottomView.frame.size.height-20;

  
    //初始化其他按钮
    [self initOtherButtons];
   
    
    //注册通知，接收锁屏，前台事件
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationStateNotice:) name:nil object:nil];
    
}

#pragma mark  接收应用锁屏，前台事件的响应函数
-(void)applicationStateNotice:(NSNotification *)noti
{
    if ([noti.name isEqualToString:@"downloadResume"]) {
        NSLog(@"resume object=%@",noti.object);
        if ([noti.object intValue] == 0) {
                 [_downloadTask resume];
           
        }
        else
        {
            if (_downloadFlag == 300) {//锁屏重新进入后，重新下载
                [self downZipFromServer];

            }
            
        }
    }
    else if ([noti.name isEqualToString:@"downloadPause"])
    {//锁屏或者进入后台的时候，暂停音频播放
        if (self.calloutView.isPlaying) {
            [self.calloutView.player pause];
            UIImageView *v = [self.calloutView viewWithTag:1011];
            v.image = [UIImage imageNamed:@"yuying-2.png"];
        }
        self.calloutView.player = nil;
        
        NSLog(@"object=%@",noti.object);
        if ([noti.object intValue] == 0) {
                 [_downloadTask suspend];

        }
        else
        {
            if (_downloadTask) {
                self.downloadFlag = 300;
                [_downloadTask cancel];
                _downloadTask = nil;
            }
            
        }
       
    }
    
}

#pragma  mark -设置导航栏
-(void)setNavigationBar
{
    
//    //设置导航栏的背景色
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg.png"] forBarMetrics:UIBarMetricsDefault];
//    //改变字体颜色
//    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
//    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    self.navigationController.navigationBar.titleTextAttributes = textAttrs;

    [Manager setNavi:self.navigationController.navigationBar];
    
    //设置导航栏的返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(backBtnIsClicked:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    //设置本页的标题
    self.navigationItem.title = @"电子导游";
}

#pragma mark - 导航栏backBtn被点击
- (void)backBtnIsClicked:(UIButton *)Btn {

    /*新改－－消除弹出气泡的饮品播放*/
    if (self.calloutView.isPlaying) {
        [self.calloutView.player pause];
    }
    self.calloutView.player = nil;
    /*新改*/
    
    //下载任务停止
    WS(ws);
    if (self.downloadTask) {
        _downloadProgressV = nil;
        ws.downloadTask = nil;
        ws.session = nil;
    }
    
    if(self.mapView.locationDisplay.dataSourceStarted){
        [self.mapView.locationDisplay stopDataSource];
        self.mapView.rotationAngle = 0;
        
    }
    
    [self dismissViewControllerAnimated:NO completion:^{
       
        [self removeAllViews];
    }];
    MapInfo *info = [MapInfo shareMapInfo];
    info.isFirstLoad = NO;
}


#pragma mark -初始化地图，设置地图的视图
-(void)initMapView
{
    //去除水印
 //   [AGSRuntimeEnvironment setClientID:@"s7yYRgNddiYJ0yDo" error:nil];
    
    self.mapView = [[AGSMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-49)];
    
    //1.判断有没有缓存的地图，有缓存的地图，加载缓存的地图 2.无缓存的地图，判断有网没网，有网加载有线地图，没网提示没网
    NSString *cachesPath = [FileDownloadTool getTheCachePath];
    cachesPath = [cachesPath stringByAppendingString:@"/create_scenic_area_info/Basic.tpk"];
    NSLog(@"cachePath = %@",cachesPath);
   
    MapInfo *info = [MapInfo shareMapInfo];
    BOOL mapExist = [FileDownloadTool whetherFileExist:cachesPath];
    if (mapExist) {
        AGSLocalTiledLayer* layer = [AGSLocalTiledLayer localTiledLayerWithPath:cachesPath];
        [self.mapView addMapLayer:layer withName:@"base Tiled Layer"];
        info.isOfflineLoad = YES;
    }
    else
    {
        info.isOfflineLoad = NO;

        MapInfo *info = [MapInfo shareMapInfo];
        if (info.internetStatus == -1 || info.internetStatus == 0)
            [FileDownloadTool alert:@"亲，您的网络似乎出了点问题" view:self.view];
        
        else{
            if (info.isFirstLoad  == NO) {
                info.isFirstLoad = YES;
                [FileDownloadTool alert:@"正在加载，请稍后" view:self.view];
            }
        }
        
        //显示地图
        NSString *baseMapUrl =@"http://218.108.4.35:6080/arcgis/rest/services/Basic/MapServer";
        AGSTiledMapServiceLayer *baseMap =[[AGSTiledMapServiceLayer alloc]initWithURL:[NSURL URLWithString:baseMapUrl]];
        //地图添加底图
        [self.mapView addMapLayer:baseMap withName:@"TiledMapLayer"];
    }
    //设置地图可两指捏拉缩放
    self.mapView.allowRotationByPinching = YES;
    //设置代理
    self.mapView.touchDelegate = self;
    self.mapView.layerDelegate =self;
    
    //设置地图可环绕
    [self.mapView enableWrapAround];
    //去掉网格线，将网格线的宽度设为0
    self.mapView.gridLineWidth = 0;
    //设置地图的背景色
    self.mapView.backgroundColor = [UIColor whiteColor];
    
    self.mapView.minScale = 100000.00;
    
    
    [self.view addSubview:self.mapView];
    [self.view bringSubviewToFront:_bottomView];
    
}



//初始化其他按钮
-(void)initOtherButtons
{
    self.downloadBtn = [[UIButton alloc]init];
    [self.downloadBtn setBackgroundImage:[UIImage imageNamed:@"download.png"] forState:UIControlStateNormal];
    self.downloadBtn.tag = 10;
    [self.downloadBtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.compassBtn = [[UIButton alloc]init];
    self.compassBtn.tag = 11;
    [self.compassBtn setBackgroundImage:[UIImage imageNamed:@"compass.png"] forState:UIControlStateNormal];
    [self.compassBtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.locationBtn = [[UIButton alloc]init];
    self.locationBtn.tag = 12;
    [self.locationBtn setBackgroundImage:[UIImage imageNamed:@"location_default"] forState:UIControlStateNormal];
    [self.locationBtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *enlargebtn = [[UIButton alloc]init];
    enlargebtn.tag = 13;
    [enlargebtn setBackgroundImage:[UIImage imageNamed:@"enlarge_default.png"] forState:UIControlStateNormal];
    [enlargebtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *lessenBtn = [[UIButton alloc]init];
    lessenBtn.tag = 14;
    [lessenBtn setBackgroundImage:[UIImage imageNamed:@"lessen_default.png"] forState:UIControlStateNormal];
    [lessenBtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
#pragma mark --路径规划按钮初始化，图片和点击事件绑定(路径规划)
  /*  _routeTaskBtn = [[UIButton alloc]init];
    _routeTaskBtn.tag = 15;
    [_routeTaskBtn setBackgroundImage:[UIImage imageNamed:@"routing.png"] forState:UIControlStateNormal];
    [_routeTaskBtn setBackgroundImage:[UIImage imageNamed:@"routing_selected.png"] forState:UIControlStateSelected];
    [_routeTaskBtn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_routeTaskBtn];
   */
    
    
 /*废弃
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    //设置委托对象为自己
    [_locationManager setDelegate:self];
    
    //要求CLLocationManager对象返回全部结果
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    //30.3136  120.2547222
    //要求CLLocationManager对象的返回结果尽可能的精准
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    // 取得定位权限，有两个方法，取决于你的定位使用情况
    // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
    [_locationManager requestWhenInUseAuthorization];//这句话ios8以上版本使用。
*/
    
    [self.view addSubview:self.downloadBtn];
    [self.view addSubview:self.compassBtn];
    [self.view addSubview:self.locationBtn];
    [self.view addSubview:enlargebtn];
    [self.view addSubview:lessenBtn];


    _searchView =[[MySearchView alloc]init];
    _searchView.delegate = self;
    [self.view addSubview:_searchView];
    
    WS(ws);
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        if (IS_IPHONE6_UP) {
            make.width.mas_equalTo(320);
            make.height.mas_equalTo(33.3);
            
        }
        else
        {
            make.width.mas_equalTo(240);
            make.height.mas_equalTo(30);
        }
        make.centerX.equalTo(ws.view.mas_centerX);
        make.top.equalTo(ws.view.mas_top).with.offset(75);
    }];
    
    
    //给其他按钮添加约束
        [self.downloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_searchView.mas_left);
            if (IS_IPHONE6_UP) {
                make.top.equalTo(_searchView.mas_bottom).offset(10);
                make.height.mas_equalTo(40);
                make.width.mas_equalTo(40);
            }
            else
            {
                make.top.equalTo(_searchView.mas_bottom).offset(5);
                make.height.mas_equalTo(33);
                make.width.mas_equalTo(33);
            }
            
        }];
        
        [self.compassBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_downloadBtn.mas_left);
            if (IS_IPHONE6_UP) {
                make.top.equalTo(_downloadBtn.mas_bottom).offset(10);
                make.height.mas_equalTo(40);
                make.width.mas_equalTo(40);
            }
            else
            {
                make.top.equalTo(_downloadBtn.mas_bottom).offset(5);
                make.height.mas_equalTo(33);
                make.width.mas_equalTo(33);
            }
            
        }];
        
        [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_downloadBtn.mas_left);
            if (IS_IPHONE6_UP) {
                make.top.equalTo(_compassBtn.mas_bottom).offset(10);
                make.height.mas_equalTo(40);
                make.width.mas_equalTo(40);
            }
            else
            {
                make.top.equalTo(_compassBtn.mas_bottom).offset(5);
                make.height.mas_equalTo(33);
                make.width.mas_equalTo(33);
            }
            
        }];
   
    [enlargebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_searchView.mas_right);
        if (IS_IPHONE6_UP) {
            make.top.equalTo(_searchView.mas_bottom).offset(10);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(40);
        }
        else
        {
            make.top.equalTo(_searchView.mas_bottom).offset(5);
            make.height.mas_equalTo(33);
            make.width.mas_equalTo(33);
        }
    }];

    [lessenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_searchView.mas_right);
        if (IS_IPHONE6_UP) {
            make.top.equalTo(enlargebtn.mas_bottom).offset(10);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(40);
        }
        else
        {
            make.top.equalTo(enlargebtn.mas_bottom).offset(5);
            make.height.mas_equalTo(33);
            make.width.mas_equalTo(33);
        }
    }];

#pragma mark --路径规划的按钮位置确定
    /*
   [_routeTaskBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lessenBtn.mas_right);
        if (IS_IPHONE6_UP) {
            make.top.equalTo(lessenBtn.mas_bottom).offset(10);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(40);
        }
        else
        {
            make.top.equalTo(lessenBtn.mas_bottom).offset(5);
            make.height.mas_equalTo(33);
            make.width.mas_equalTo(33);
        }
    }];
 */
    

}


//初始化路线视图
-(void)initRouteView
{
    if (IS_IPHONE6_UP)
        _routeView = [[RouteView alloc]initWithFrame:CGRectMake(44,self.view.frame.size.height-56-230 , 272, 230)];
    else
         _routeView = [[RouteView alloc]initWithFrame:CGRectMake(44,self.view.frame.size.height-56-162 , 230, 162)];
    
    _routeView.delegate = self;
    //默认选中第一个入口
    [self.routeView.entryTable selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    //实现点击第一行所调用的方法
    [self.routeView tableView:self.routeView.entryTable didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    [self.view addSubview:_routeView];
 

}


//初始化标签视图，collectionView
-(void)initCollectionView
{
    //初始化button的normal状态的图片数组
    
    self.normalImgArr = @[@"gtstraveling.png",
                          @"gtsplay.png",
                          @"food.png",
                          @"hotel.png",
                          @"parking.png",
                          @"wc.png",
                          @"serviceCenter.png"];
    //初始化button的elect状态的图片数组
    self.selectImgArr = @[@"gtstraveling-select.png",
                          @"gtsplay-select.png",
                          @"food-select.png",
                          @"hotel-select.png",
                          @"parking-select.png",
                          @"wc-select.png",
                          @"serviceCenter-select.png"];
    //初始化标签的名字数组
    self.markLabelNameArr =@[@"游在皋亭",
                             @"娱在皋亭",
                             @"吃在皋亭",
                             @"住在皋亭",
                             @"车位",
                             @"厕所",
                             @"游客中心"];

    
    //设置collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    if (IS_IPHONE6_UP) {
        self.markCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-225-33, self.view.frame.size.height-170-56, 250, 170) collectionViewLayout:layout];
    }
    else
    {
        self.markCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-205-33, self.view.frame.size.height-140-56, 230, 140) collectionViewLayout:layout];
    }
    self.markCollectionView.contentSize=CGSizeMake(0, 0);
    self.markCollectionView.delegate = self;
    self.markCollectionView.dataSource = self;
    [self.view addSubview:self.markCollectionView];
    [self.markCollectionView registerClass:[MarkCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

}


#pragma mark -other buttons clicked event,tag值和markView上的8个button区分开
-(void)otherBtnClicked:(UIButton *)sender
{
    unsigned long tag = (unsigned long)sender.tag;
    switch (tag) {
           
        case 10:
        {
            WS(ws);
            _downloadFlag = 0;
            _downloadProgressV = nil;
            ws.downloadTask = nil;
            ws.session = nil;

            //check th networkStatus
            if (![AFNetworkReachabilityManager sharedManager].reachable) {
                [FileDownloadTool alert:@"亲，您的网络似乎有点问题" view:self.view];
                return;
            }
            NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            cache = [cache stringByAppendingString:@"/create_scenic_area_info.zip"];
            _total = [FileDownloadTool fileSizeAtPath:cache];
            NSLog(@"folder = %lld ",_total);
            
            //判断是否已经下载地图包
            UIAlertController *alertview=[UIAlertController alertControllerWithTitle:@"下载离线包" message:@"是否下载地图离线包？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *defult = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self downZipFromServer];
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                
            [alertview addAction:cancel];
            [alertview addAction:defult];
            [self presentViewController:alertview animated:YES completion:nil];
        
            break;
        }
        case 11:{
             //compass(罗盘功能)
            _locationManager = [[CLLocationManager alloc] init];
            // 设置代理
            //设置委托对象为自己
            [_locationManager setDelegate:self];
            if (sender.selected ==NO) {
                if ([CLLocationManager headingAvailable]) {
                    [self.locationManager startUpdatingHeading];
                }
            }
            else
            {
                self.compassBtn.transform = CGAffineTransformMakeRotation(0);
                self.mapView.rotationAngle = 0;
                [self.mapView zoomToScale:200000 animated:YES];
                [self.locationManager stopUpdatingHeading];
            }
            sender.selected = !sender.selected;
            break;
        }
        case 12:
        {
            //判断定位的点是否在当前地图范围内，如果在，就居中显示当前点，
            BOOL isInMap = [FMDataBaseTool whetherInMapPolygon:[FMDataBaseTool transferToMapViewSpatialreference:self.mapView.locationDisplay.mapLocation]];
            
            if (isInMap) {
                [self.mapView centerAtPoint:[FMDataBaseTool transferToMapViewSpatialreference:self.mapView.locationDisplay.mapLocation] animated:YES];
            }
            else
            {
                [FileDownloadTool alert:@"您不在景区范围内" view:self.view];
                [self.mapView zoomToScale:250000 animated:YES];
            }
            
            break;
        }
        case 13:
        {
            //enlarge
             NSLog(@"self.mapview.scale = %f",self.mapView.mapScale);
            [self.mapView zoomIn:YES];
            break;
        }
        case 14:
        {
            //lessen
            [self.mapView zoomOut:YES];
            break;
        }
        default:
        {
            /*路径规划按钮点击事件*/
            /*
                self.taskAlert=[UIAlertController alertControllerWithTitle:@"路径规划" message:@"您选择手动输入规划还是轻触屏幕规划？" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *defult = [UIAlertAction actionWithTitle:@"手动输入" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    self.isTapRouting = YES;
                    [self excuteInputRouting];
                }];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"点击屏幕" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    //2.添加当前位置为起点
                    AGSPoint *po = [self addCuWithStart];
                    if (po) {
                        [FileDownloadTool alert:@"单击地图选择终点" view:self.view];
                        
                        [self addStop:po type:1];
                        if(self.routeTaskParams){
                            self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
                        }
                    }
                    
                }];
                
                [self.taskAlert addAction:cancel];
                [self.taskAlert addAction:defult];
                [self presentViewController:self.taskAlert animated:YES completion:nil];
           */
                break;
        }
            
    }
}



#pragma mark BottomViewDelegate地图底部按钮切换事件
//底部按钮的按钮点击事件，按钮的click属性在bottomView中变化，然后将参数传过来，根据参数，做相应的视图弹出，收起操作
-(void)displayWithBtn:(unsigned long)tag andClick:(BOOL)click
{
    MapInfo *info = [MapInfo shareMapInfo];
    if (info.internetStatus == -1 || info.internetStatus == 0){
        [FileDownloadTool alert:@"您的网络似乎出了点问题" view:self.view];
    }
    else{
        if (info.isFirstLoad  == NO) {
            info.isFirstLoad = YES;
            [FileDownloadTool alert:@"正在加载，请稍后" view:self.view];
        }
    }
    
    if (tag==101) {
        //显示标签页，隐藏路线页面
        [self.routeLayer removeAllGraphics];
        [self.entryMarkLayer removeAllGraphics];
        [self.routeView setHidden:YES];
        if (click == NO) {
            if (self.markCollectionView ==nil)
                [self initCollectionView];
            else
                [self.markCollectionView setHidden:NO];
        }
        else
        {
            [self.markCollectionView setHidden:YES];
        }
    }
    
    if (tag==100) {
        [self.markCollectionView setHidden:YES];
        [self.markLayer removeAllGraphics];
        [self.ridingFeatureTableLayer setVisible:NO];
        [self.youbuFeatureTableLayer setVisible:NO];
        [self.biaojiImgV removeFromSuperview];

        if (click == NO) {
            //显示路线页面页，隐藏标签页面
            if (self.routeView ==nil)
                [self initRouteView];
            else
                [self.routeView setHidden:NO];

        }
        else
        {
            [self.routeView setHidden:YES];
        }
    }
    
    
    if (tag!=100) {
        //关闭路线页面的导航
        [self.locationManager stopUpdatingHeading];
        self.compassBtn.selected =NO;
        self.compassBtn.transform = CGAffineTransformMakeRotation(0);
    }
    
}

#pragma mark routeViewDelegate选中线路，添加路线(底部路线标签按钮点击弹出的视图事件)
//通过routeView的routeTable的点击事件，传过来的参数，将GraphicArr直接添加到图层上，地图缩到原来的比例
-(void)transferRouteId:(NSArray *)graphicArr
{
    if ([[self.entryMarkLayer graphics] count] == 0) {
        NSLog(@"hello");
        [self.entryMarkLayer addGraphic:self.entryGra];
    }
     [self.routeLayer removeAllGraphics];
    [self.routeLayer addGraphics:graphicArr];
    [self.mapView zoomToScale:100000 animated:YES];
}

#pragma mark 点击入口的时候，入口标记，并且移到屏幕中央，地图放大
-(void)transferEntryGraphic:(AGSGraphic *)graphic andPoint:(AGSPoint *)point
{
    [self.entryMarkLayer removeAllGraphics];
    self.entryGra = graphic;
    [self.routeLayer removeAllGraphics];
    [self.entryMarkLayer addGraphic:graphic];
    [self.mapView centerAtPoint:point animated:YES];
    [self.mapView zoomToScale:10080.9 animated:YES];
}


#pragma mark -地图API的定位监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    //位置改变后的处理函数
    if ([keyPath isEqual:@"location"]){
       
    }
}

#pragma mark mapview delegate地图加载完后，记录下初始的显示范围，便于后面将地图缩放到原比例
-(void)mapViewDidLoad:(AGSMapView *)mapView
{
 
    [self.mapView zoomToScale:100000 animated:YES];//控制地图的显示比例，比例越大，地图越小，地点看的越补清楚
    self.originalEnvelope = self.mapView.visibleAreaEnvelope;
    //存储地图的spatialReference
  
    MapInfo *info = [MapInfo shareMapInfo];
    info.mapSpatialReference = self.mapView.spatialReference;
  
    //注册通知，地图一显示就开始定位
    //Listen to KVO notifications for map gps's autoPanMode property
    [self.mapView.locationDisplay addObserver:self
                                   forKeyPath:@"location"
                                      options:(NSKeyValueObservingOptionNew)
                                      context:NULL];
    
    //Start the map's gps if it isn't enabled already
    if(!self.mapView.locationDisplay.dataSourceStarted)
        [self.mapView.locationDisplay startDataSource];
    
    self.mapView.locationDisplay.autoPanMode = AGSLocationDisplayAutoPanModeDefault;
    
    self.mapView.locationDisplay.wanderExtentFactor = 0.75;
    
    
    if (!info.isOfflineLoad) {
        //给地图添加上游步道,离线地图已经做好，这是有线情况，离线已经加好了
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"na" ofType:@"geodatabase"];
        NSError *error;
        AGSGDBGeodatabase *gdb = [[AGSGDBGeodatabase alloc]initWithPath:filePath error:&error];
        for (AGSFeatureTable* fTable in gdb.featureTables) {
            if ([fTable hasGeometry] && [fTable.tableName isEqualToString:@"游步道"]==YES) {
                [self.mapView addMapLayer:[[AGSFeatureTableLayer alloc]initWithFeatureTable:fTable] withName:@"youbuBase"];
            }
        }
        
        //添加游步道和骑行道(用于“游在皋亭”的道路显示)，必须要在大头针图层之前添加，不然会盖住大头针
        
        [self addYoubuAndRidingRoadToMapview];
        [_youbuFeatureTableLayer setVisible:NO];
        [_ridingFeatureTableLayer setVisible:NO];
    }
    
   
    
    self.baseMarkLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.baseMarkLayer withName:@"baseMarkLayer"];
    NSDictionary *parameter = [[NSDictionary alloc]initWithObjectsAndKeys:@"1",@"type", nil];
    [Manager getInformationForType:parameter andBlock:^(NSArray *modelArr) {
        NSArray *graphicArr = [Manager graphicArrByAttracModelArr:modelArr andType:@"1"];
        [self.baseMarkLayer addGraphics:graphicArr];
    }];

    //提前添加地图上的入口标记的图层，在选择入口的时候，会标记入口
    self.entryMarkLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.entryMarkLayer withName:@"entryMarkLayer"];
    //提前添加地图上的路线图层，线路选择后，画路线的涂层
    self.routeLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.routeLayer withName:@"routeGraphicsLayer"];
    
#pragma mark --路径规划，提前添加图层，保持地图的层次关系
  /*  self.graphicsLayerRoute = [self routeTaskResultLayer];
    [self.mapView addMapLayer:self.graphicsLayerRoute withName:@"RoutetaskLayer"];
    
    // add graphics layer for displaying the stops
    self.graphicsLayerStops = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.graphicsLayerStops withName:@"StopsLayer"];
    */
    
    
    //给地图添加，标签图层(添加点击标签按钮出现水滴的图层)
    self.markLayer = [AGSGraphicsLayer graphicsLayer];
    [self.mapView addMapLayer:self.markLayer withName:@"markGraphicsLayer"];
    //set the callout delegate so we can display callouts,弹出气泡代理
    self.markLayer.calloutDelegate = self;
    
    /**新改0715如果是从景点详情点击跳转的地图，进入后开线程请求点的消息**/
    if (_fromAttractionMap) {
            NSDictionary *parameter = [[NSDictionary alloc]initWithObjectsAndKeys:self.spotName,@"name",self.spotCode,@"code", nil];
            [Manager getInformationForType:parameter andBlock:^(NSArray *modelArr) {
                NSArray *graphicArr = [Manager spotsGraphicArrWithModelArr:modelArr];
                [self.markLayer addGraphics:graphicArr];
            }];
        if ([self.spotName isEqualToString:@"登山游步道"]) {
            [_youbuFeatureTableLayer setVisible:YES];
        }
        if ([self.spotName isEqualToString:@"骑行赛道"]) {
            [_ridingFeatureTableLayer setVisible:YES];
        }
    }
    
#pragma mark --路径规划管理对象的初始化(路径规划)
  /*  NSError *error;
    self.routeTask = [AGSRouteTask routeTaskWithDatabaseName:@"na" network:@"roads_ND" error:&error];
    self.routeTask.delegate = self;
    [self.routeTask retrieveDefaultRouteTaskParameters];
    self.numStops = 0;
   */
}

#pragma mark -地图单击事件--AGSMapViewTouchDelegate
//点击地图，底部的弹出视图收起
-(void)mapView:(AGSMapView *)mapView didClickAtPoint:(CGPoint)screen mapPoint:(AGSPoint *)mappoint features:(NSDictionary *)features
{
    NSLog(@"map.x= %f ,map.y = %f",mappoint.x,mappoint.y);
    /*新改*/
    if (self.calloutView.isPlaying) {
        [self.calloutView.player pause];
    }
    self.calloutView.player = nil;
    /*新改*/
    
    [self.markCollectionView setHidden:YES];
    [self.routeView setHidden:YES];
    [self.resultTable setHidden:YES];
    
    //注册通知，视图收起后，通知bottomView的button，恢复成未click状态

    [_bottomView changeState];
    [self.searchView.searchTextField resignFirstResponder];
    [self.searchView.cancelBtn setHidden:YES];
    
    
 /**路径规划 添加终点（路径规划）**/
 /*   if (self.isTapRouting ) {
       [self addStop:mappoint type:2];
        if(self.graphicsLayerStops.graphics.count>1){
            [self solveRoute];
        }
        if(self.routeTaskParams){
            self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
        }
    }
   */
}


#pragma mark -地图长按事件
-(void)mapView:(AGSMapView *)mapView didTapAndHoldAtPoint:(CGPoint)screen mapPoint:(AGSPoint *)mappoint features:(NSDictionary *)features
{
    [self.entryMarkLayer removeAllGraphics];
    [self.routeLayer removeAllGraphics];
    [self.markLayer removeAllGraphics];
    [self.mapView.callout dismiss];
    [self.mapView zoomToScale:100000 animated:YES];
    
    //路径规划相关的重置
/*    self.numStops = 0;
    [self.graphicsLayerStops removeAllGraphics];
    [self.graphicsLayerRoute removeAllGraphics];
 */
}

#pragma mark -AGSCalloutDelegate弹出气泡(只有人文景观，农家乐，游客中心弹气泡,其它直接点击跳转)
-(BOOL)callout:(AGSCallout *)callout willShowForFeature:(id<AGSFeature>)feature layer:(AGSLayer<AGSHitTestable> *)layer mapPoint:(AGSPoint *)mapPoint
{
    /**0714注释**/
    /**
    if ([layer.name isEqualToString:@"markGraphicsLayer"]==YES) {
        AGSGraphic* graphic = (AGSGraphic*)feature;
        if ([[[graphic allAttributes] objectForKey:@"graphicType"] isEqualToString:@"2"]) {
            AttractionDetailController *at = [[AttractionDetailController alloc]init];
            at.titleString = [[graphic allAttributes] objectForKey:@"graphicName"];
            at.code = [[graphic allAttributes] objectForKey:@"graphicCode"];
            [self.navigationController pushViewController:at animated:YES];
            return NO;
        }
        if ([[[graphic allAttributes] objectForKey:@"graphicType"] isEqualToString:@"3"]) {//停车场不用弹气泡
            return NO;
        }
        CalloutView *callView = [[CalloutView alloc]initWithFrame:CGRectMake(0, 0, 133, 93)];
        callView.delegate = self;
        //对名字做处理，如果是农家乐，括号里面内容减掉
        callView.objectNameLab.text =[JsonAnalysisTool deleteCharactersInBrackets:[graphic attributeAsStringForKey:@"graphicName"]];
        //如果名字过长，名字字体变小
        NSString *str = callView.objectNameLab.text;
        NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};
        CGSize labelSize= [str sizeWithAttributes:attrs];
        if (labelSize.width > callView.objectNameLab.frame.size.width) {
            callView.objectNameLab.font = [UIFont systemFontOfSize:9];
        }
        callView.objectCode =[graphic attributeAsStringForKey:@"graphicCode"];
     
        self.mapView.callout.customView = callView;
        self.mapView.callout.borderColor = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:0];
        
        self.mapView.callout.color = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:0];
        self.mapView.callout.accessoryButtonHidden = YES;
    }
    
    return YES;  **/
    /*新改 */
    
    if ([layer.name isEqualToString:@"markGraphicsLayer"]==YES) {
        AGSGraphic* graphic = (AGSGraphic*)feature;
        
        //如果是停车场和厕所，游客中心，不用弹气泡
        if ([graphic attributeAsStringForKey:@"graphicType"]==nil || [[graphic attributeAsStringForKey:@"graphicType"] isEqualToString:@"6"] || [[graphic attributeAsStringForKey:@"graphicType"] isEqualToString:@"7"]) {
            return NO;
        }
        CGFloat width = self.view.frame.size.width - 150;
        CGFloat height = width / 1.85 + 40;
        SpotCallout *callView = [[SpotCallout alloc]initWithFrame:CGRectMake(0, 0, width, height) andImg:[graphic attributeAsStringForKey:@"graphicImg"]];
        callView.spotPoint = mapPoint;
        callView.delegate = self;
        callView.nameLab.text = [NSString stringWithFormat:@"      %@",[Manager deleteCharactersInBrackets:[graphic attributeAsStringForKey:@"graphicName"]]];
        callView.keyword = [graphic attributeForKey:@"graphicKey"];
        callView.audioUrl = [graphic attributeAsStringForKey:@"graphicAudio"];
        callView.spotCode = [graphic attributeAsStringForKey:@"graphicCode"];
        if (![[graphic attributeAsStringForKey:@"graphicAudio"] isEqualToString:@""]) {
            callView.btnCount = 2.0;//有音频文件，就显示两个按钮
        }
        else
        {
            callView.btnCount = 1.0;
        }
        [callView setBtns];
        
        self.mapView.callout.customView = callView;
        self.mapView.callout.borderColor = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:0];
        
        self.mapView.callout.color = [UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:0];
        
        //hide the accessory view and also the left image view.
        self.mapView.callout.accessoryButtonHidden = YES;
        self.calloutView = callView;
    }
    
    return YES;

}

#pragma mark -calloutView的代理事件
//点击气泡”景点介绍“触发的函数,代理函数，跳转到景点详情
-(void)pushToDetailPage:(NSString *)thCode andObjectName:(NSString *)name
{
    if (_fromAttractionMap) {
        [self.mapView.callout dismiss];
        [self dismissViewControllerAnimated:NO completion:nil];
        return;
    }
    AttractionDetailController *at = [[AttractionDetailController alloc]init];
    at.titleString = name;
    at.code = thCode;
    at.isFromGuid = YES;
    UINavigationController *na= [[UINavigationController alloc]initWithRootViewController:at];
    [self presentViewController:na animated:NO completion:nil];
}



/*
#pragma mark -the delegate for CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if (self.flag == 1) {
        NSLog(@"locations.count = %ld",(unsigned long)locations.count);
        CLLocation *newLocation = [locations objectAtIndex:0];
        NSLog(@"新的经度＝%lf",newLocation.coordinate.longitude);
        NSLog(@"新的纬度＝%lf",newLocation.coordinate.latitude);
        //转化
        // 获取当前所在的城市名
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //根据经纬度反向地理编译出地址信息
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
            if (array.count > 0){
                CLPlacemark *placemark = [array objectAtIndex:0];
                //将获得的所有信息显示到label上
                NSLog(@"信息＝%@",placemark.name);
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                NSLog(@"city = %@", city);
                
            }
            else if (error == nil && [array count] == 0)
            {
                NSLog(@"No results were returned.");
            }
            else if (error != nil)
            {
                NSLog(@"An error occurred = %@", error);
            }
        }];
        //显示当前定位的位置
        AGSPoint *point = [[AGSPoint alloc]initWithX:newLocation.coordinate.longitude y:newLocation.coordinate.latitude spatialReference:self.mapView.spatialReference];
        //判断点在不在地图范围内
        BOOL isInMap = [FMDataBaseTool whetherInMapPolygon:point];
        if (!isInMap) {
            NSLog(@"抱歉，你不在景区内");
//           UIAlertController *alert= [UIAlertController alertControllerWithTitle:@"无法定位" message:@"抱歉，您不在景区内" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
//        
//            }];
//            [alert addAction:okAction];
//            
//            [self presentViewController:alert animated:YES completion:nil];
            
            [FileDownloadTool alert:@"抱歉，您已超出景区范围" view:self.view];
            
        }
        else
        {
            AGSPictureMarkerSymbol *pt=[AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:@"circle.jpg"];
            AGSGraphic * graphic = [[AGSGraphic alloc]initWithGeometry:point symbol:pt attributes:nil];
            [self.routeLayer addGraphic:graphic];
            [self.mapView centerAtPoint:point animated:YES];
            
        }
        //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
        [manager stopUpdatingLocation];

    }
    else if(self.flag == 2)
    {
        //点击线路规划的时候，定位
//        CLLocation *currentLocation = [locations objectAtIndex:0];
//        AGSPoint *currentPoint = [[AGSPoint alloc]initWithX:currentLocation.coordinate.longitude y:currentLocation.coordinate.latitude spatialReference:[AGSSpatialReference wgs84SpatialReference]];
//        AGSPoint *point = [FMDataBaseTool transferToMapViewSpatialreference:currentPoint];
//        MapInfo *info = [MapInfo shareMapInfo];
//        info.currentLocationForRoute = point;
       
        AGSPoint *currentPoint = [[AGSPoint alloc]initWithX:120.216189596 y:30.3892879800001 spatialReference:[AGSSpatialReference wgs84SpatialReference]];
        AGSPoint *point = [FMDataBaseTool transferToMapViewSpatialreference:currentPoint];
        [self addStop:point];
        if(self.routeTaskParams){
            self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
        }
        [manager stopUpdatingLocation];
    }
}
*/


#pragma mark -方向改变，地图旋转，指南针转动
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    [self.mapView zoomToScale:20000 animated:YES];
    CGAffineTransform transform = CGAffineTransformMakeRotation(-1*degreesToRadians(newHeading.magneticHeading));
    self.compassBtn.transform = transform;
    self.mapView.rotationAngle=newHeading.magneticHeading;
}



#pragma mark -collectionView dataSources
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 7;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
    static NSString *str = @"cell";
    MarkCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:str forIndexPath:indexPath];
    [cell setBtnNormalImage:[self.normalImgArr objectAtIndex:indexPath.row] andLabelText:[self.markLabelNameArr objectAtIndex:indexPath.row]];
    [cell setBtnSelectImage:[self.selectImgArr objectAtIndex:indexPath.row]];
    
     //加载之前，判断页面是否已经点击过按钮，按钮状态是怎么样的
    if (self.currentSelectIndex.row ==indexPath.row) {
        cell.markbtn.selected =self.state;
    }
    cell.markbtn.tag = indexPath.row+200;//区分系统自分配的tag值，和bottomview的夜区分
    [cell.markbtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
   
    return cell;
}


#pragma mark -collectionView delegate

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return NO;
}

#pragma mark -UICollectionViewDelegateLayout
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.markCollectionView.frame.size.width-25)/4-5, (self.markCollectionView.frame.size.height-15)/2);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5) ;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5;
}


#pragma mark -自定义collectionView cell button click
//标签视图上的按钮点击事件，显示对应标签
-(void)btnClicked:(UIButton *)sender
{
    //collectionView上的button切换时，先把之前的callOut移除掉，再加载新的
    [self.mapView.callout dismiss];

    //获取当前点击的button，所在cell的indexPath
    UIView *v = [sender superview];
    MarkCollectionViewCell *cell = (MarkCollectionViewCell *)v;
    NSIndexPath *indexpath = [self.markCollectionView indexPathForCell:cell];
    
    cell.markbtn.selected = ! cell.markbtn.selected;
    
    //保存当前选中行，并且保存当前按钮点击后的状态，用于加载的时候，上次操作的按钮保持上次操作的状态
    self.currentSelectIndex = indexpath;
    self.state = cell.markbtn.selected;

    [self setOtherBtn:indexpath];//将其它按钮恢复原状
    
    [self.mapView zoomToScale:100000 animated:YES];//地图恢复到原来的大小
    
    [self.markLayer removeAllGraphics];//每次选中按钮的时候，先将之前的全部移除
    [_youbuFeatureTableLayer setVisible:NO];
    [_ridingFeatureTableLayer setVisible:NO];
    [_biaojiImgV removeFromSuperview];
    if (sender.selected == NO)
    {
        return;//未选中状态，直接返回
    }
    
    if (indexpath.row == 0) {
        //游在皋亭，要加上游步道和骑行道，还有标记路线的小图片
        [self setRoadBiaoJiImg];
        [_youbuFeatureTableLayer setVisible:YES];
        [_ridingFeatureTableLayer setVisible:YES];
    }
    /**新改**/
    if (indexpath.row == 4) {
        //从力石请求停车场信息
        XMLAnalysisTool *too = [[XMLAnalysisTool alloc]init];
        [too analysisXML:^(NSArray *modelArr) {
            NSArray *graArr = [Manager graphicArrByAttracModelArr:modelArr andType:@"5"];
            [self.markLayer addGraphics:graArr];
        }];
        
        return;
    }
    
    //从服务器获取数据，并放到地图上
  
       NSDictionary *parameter = [[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)indexpath.row+1],@"type", nil];
       [Manager getInformationForType:parameter andBlock:^(NSArray *modelArr) {
           NSArray *graphicArr = [Manager spotsGraphicArrWithModelArr:modelArr];
           [self.markLayer addGraphics:graphicArr];
       }];
    
    [self.mapView zoomToScale:100000 animated:YES];

}

#pragma mark --游步道和骑行道区分图片设置
-(void)setRoadBiaoJiImg
{
    if (!_biaojiImgV) {
        _biaojiImgV = [[UIImageView alloc]init];
    }
        _biaojiImgV.image = [UIImage imageNamed:@"biaoji"];
        [self.view addSubview:_biaojiImgV];
        
    [_biaojiImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        WS(ws);
        make.left.equalTo(ws.bottomView.mas_left).offset(20);
        make.bottom.equalTo(ws.bottomView.mas_top).offset(-40);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(80);
    }];
}

#pragma mark 给地图添加游步道，和骑行道
-(void)addYoubuAndRidingRoadToMapview
{
    
    NSError *error;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"na" ofType:@"geodatabase"];
    AGSGDBGeodatabase *gdb = [[AGSGDBGeodatabase alloc]initWithPath:filePath error:&error];
    for (AGSFeatureTable* fTable in gdb.featureTables) {
        if ([fTable hasGeometry] && [fTable.tableName isEqualToString:@"游步道"]==YES) {
            _youbuFeatureTableLayer = [[AGSFeatureTableLayer alloc]initWithFeatureTable:fTable];
            UIColor *green = [UIColor colorWithRed:0/255.0 green:115/255.0 blue:76/255.0 alpha:1];
            AGSSimpleLineSymbol *lineSymbol = [[AGSSimpleLineSymbol alloc]initWithColor:green width:3.0];
             AGSSimpleRenderer*renderer = [AGSSimpleRenderer simpleRendererWithSymbol:lineSymbol];
            _youbuFeatureTableLayer.renderer = renderer;
            [self.mapView addMapLayer:_youbuFeatureTableLayer];
        }
        if ([fTable hasGeometry] && [fTable.tableName isEqualToString:@"骑行道"]==YES) {
            _ridingFeatureTableLayer = [[AGSFeatureTableLayer alloc]initWithFeatureTable:fTable];
            UIColor *yellow = [UIColor colorWithRed:225/255.0 green:155/255.0 blue:20/255.0 alpha:1];
            AGSSimpleLineSymbol *lineSymbol = [[AGSSimpleLineSymbol alloc]initWithColor:yellow width:3.0];
            AGSSimpleRenderer*renderer = [AGSSimpleRenderer simpleRendererWithSymbol:lineSymbol];
            _ridingFeatureTableLayer.renderer = renderer;
            [self.mapView addMapLayer:_ridingFeatureTableLayer];
        }
    }
}


#pragma mark -点击某个按钮，设置选中与否状态，并且将其它按钮状态改变
-(void)setOtherBtn:(NSIndexPath *)currentIndexPath
{
    int i;
    for (i=0; i<8; i++) {
        if (currentIndexPath.row ==i) {
            continue;
            
        }
        else
        {
            NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
           MarkCollectionViewCell *cell = (MarkCollectionViewCell *)[self.markCollectionView cellForItemAtIndexPath:path];
            cell.markbtn.selected = NO;
        }
    }
    [self.markLayer removeAllGraphics];
    
}


#pragma mark -MySearchViewDelegate搜索框的代理事件
-(void)passAllModel:(NSArray *)modelArr andGraphicArr:(NSArray *)graphicArr
{
    WS(ws);
    [self.searchResultModelArr removeAllObjects];
    [self.searchResultGraphicArr removeAllObjects];
    if (modelArr == nil) {
        [FileDownloadTool alert:@"关键字不能为空！" view:self.view];
        return;
    }
    
    [self.searchResultModelArr addObjectsFromArray:modelArr];
    [self.searchResultGraphicArr addObjectsFromArray:graphicArr];

    //搜索框的内容搜索出来后，直接将数据传过来，显示在tableview上
    
     if (!_resultTable) {
         _resultTable = [[UITableView alloc]init];
         [_resultTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
         _resultTable.dataSource =self;
         _resultTable.separatorStyle = NO;
         _resultTable.delegate =self;
         [self.view addSubview:_resultTable];
         //添加约束
         [_resultTable mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(ws.searchView.mas_bottom);
                    make.left.equalTo(ws.searchView.mas_left).offset(25);
                    make.right.equalTo(ws.searchView.mas_right);
                    make.height.mas_equalTo(130);
         }];
       }
       else{
            //对象存在，直接刷新数据
            [self.resultTable setHidden:NO];
            [self.resultTable reloadData];
       }

}

#pragma mark -自定义的MySearchView代理事件
-(void)hideTableView
{
    [self.markLayer removeAllGraphics];
    [self.mapView.callout removeFromSuperview];
    [self.searchResultGraphicArr removeAllObjects];
    [self.searchResultModelArr removeAllObjects];
    [self.markCollectionView setHidden:YES];
    [self.resultTable setHidden:YES];

}

#pragma mark -搜索框文本开始编辑，地图上原本的视图收起
-(void)hideSubViews
{
    [self.mapView.callout removeFromSuperview];
    [self.routeView setHidden:YES];
    [self.markCollectionView setHidden:YES];
    [self.resultTable setHidden:YES];
}

//tableview代理，事件，cell
#pragma mark -UITableView datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _searchResultModelArr.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"resultcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc]init];
        cell.textLabel.text =((MarkInfoModel *)[_searchResultModelArr objectAtIndex:indexPath.row]).objName;
    }
    return cell;
}

#pragma mark -UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.markLayer removeAllGraphics];
    [self.markLayer addGraphic:[self.searchResultGraphicArr objectAtIndex:indexPath.row]];
    self.searchView.searchTextField.text =((MarkInfoModel *)[self.searchResultModelArr objectAtIndex:indexPath.row]).objName;
    [self.searchView.searchTextField resignFirstResponder];
    [self.resultTable setHidden:YES];
}


#pragma mark --添加当前位置为当前起点(路径规划)
/*
 -(AGSPoint *)addCuWithStart
 {
 self.numStops = 0;
 self.isTapRouting = YES;// 表示点击屏幕规划
 [self.graphicsLayerStops removeAllGraphics];
 //2.添加当前位置为起点
 Singleton *single = [Singleton defaultSingleton];
 AGSPoint *cuPoint = [[AGSPoint alloc]initWithX:single.currentLocation.coordinate.longitude y:single.currentLocation.coordinate.latitude spatialReference:[AGSSpatialReference wgs84SpatialReference]];
 AGSPoint *po = [FMDataBaseTool transferToMapViewSpatialreference:cuPoint];
 //3.判断当前位置是否在地图内,不在的话直接返回
 BOOL isIn = [FMDataBaseTool whetherInMapPolygon:po];
 if (!isIn) {
 [FileDownloadTool alert:@"对不起，您不在景区范围内" view:self.view];
 self.isTapRouting = NO;
 return nil;
 }
 return po;
 }
 
 
 #pragma mark -选择手动输入，弹出路径规划图(路径规划)
 -(void)excuteInputRouting
 {
 [self.graphicsLayerStops removeAllGraphics];
 _routeTaskView = [[RouteTaskView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
 _routeTaskView.delegate = self;
 ((RouteTaskInnerView *)(_routeTaskView.innerView)).delegate = self;
 self.flag = 2;
 [self.view addSubview:_routeTaskView];
 [self.view bringSubviewToFront:_routeTaskView];
 
 }


#pragma mark --点击气泡－－－“到这里去"－－－(起点默认为“我的位置”)传递过来的终点值（路径规划）
-(void)passEndPToGuideVC:(AGSPoint *)endP
{
    //添加起点
    AGSPoint *start = [self addCuWithStart];
    if (!start) {
        return;
    }
    //如果在景区内，规划完以后，是不是因该将多余的图层去掉
    [self addStop:start type:2];
    if(self.routeTaskParams){
        self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
    }
    
  //  路径规划 添加终点
    if (self.isTapRouting ) {
        [self addStop:endP type:2];
        if(self.graphicsLayerStops.graphics.count>1){
            [self solveRoute];
        }
        if(self.routeTaskParams){
            self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
        }
    }
    
}

#pragma mark --路径规划，添加点
- (void)addStop:(AGSPoint*)geometry type:(int)tp{
    
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    NSString *imgName = [NSString stringWithFormat:@"tp_%d",tp];
    AGSPictureMarkerSymbol *symbol = [[AGSPictureMarkerSymbol alloc]initWithImageNamed:imgName];
    self.numStops++;
    
    AGSStopGraphic *stopGraphic = [AGSStopGraphic graphicWithGeometry:geometry symbol:symbol attributes:attributes];
    stopGraphic.sequence = self.numStops;
    
    [self.graphicsLayerStops addGraphic:stopGraphic];
    
}

#pragma mark - 路径规划 AGSRouteTaskDelegate

- (void)routeTask:(AGSRouteTask *)routeTask operation:(NSOperation *)op didRetrieveDefaultRouteTaskParameters:(AGSRouteTaskParameters *)routeParams {
    self.routeTaskParams = routeParams;


    self.routeTaskParams.returnRouteGraphics = YES;

    self.routeTaskParams.returnDirections = YES;


    self.routeTaskParams.findBestSequence = NO;
    
    self.routeTaskParams.returnStopGraphics = NO;

    self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;


    self.routeTaskParams.ignoreInvalidLocations = YES;
}



#pragma mark --路径规划 an error was encountered while getting defaults

- (void)routeTask:(AGSRouteTask *)routeTask operation:(NSOperation *)op didFailToRetrieveDefaultRouteTaskParametersWithError:(NSError *)error {

    
    [FileDownloadTool alert:@"Retrieve fail" view:self.view];
}


#pragma mark --路径规划，线路规划完成事件
- (void)routeTask:(AGSRouteTask *)routeTask operation:(NSOperation *)op didSolveWithResult:(AGSRouteTaskResult *)routeTaskResult {
    NSLog(@"solve success");
 
    self.routeResult = [routeTaskResult.routeResults lastObject];

    [self.graphicsLayerRoute removeAllGraphics];
    [self.graphicsLayerRoute addGraphic:self.routeResult.routeGraphic];
    self.isTapRouting = NO;
    self.numStops = 0;

}


#pragma mark --路径规划，规划失败的回调函数 solve failed

- (void)routeTask:(AGSRouteTask *)routeTask operation:(NSOperation *)op didFailSolveWithError:(NSError *)error {

    [FileDownloadTool alert:@"未找到该路线" view:self.view];
    self.numStops = 0;
    self.isTapRouting = NO;
}

 #pragma mark  --路径规划，处理路径规划的函数
-(void) solveRoute{
    
    NSMutableArray *stops = [NSMutableArray array];
    
    for (AGSGraphic *g in self.graphicsLayerStops.graphics) {
        if ([g isKindOfClass:[AGSStopGraphic class]]) {
            [stops addObject:g];
            
        }
        
    }
    
    if (stops.count > 0) {
        [self.routeTaskParams setStopsWithFeatures:stops];
        // execute the route task
       [self.routeTask solveWithParameters:self.routeTaskParams];
        
    }
}

#pragma mark -自定义RouteTaskViewDelegate，点击父视图的时候，路径规划按钮恢复为未选中（路径规划）
-(void)tapFatherViewSetButtonSelectedNo
{
    [self.routeTaskView.innerView removeFromSuperview];
    [self.routeTaskView removeFromSuperview];
    UIButton *btn = [self.view viewWithTag:15];
    btn.selected = NO;
}


#pragma mark -路径规划--子视图RouteTaskInnerViewDelegate,rout按钮点击事件（路径规划）
-(void)transferStart:(AGSPoint *)start end:(AGSPoint *)end type:(int)typ
{
    if (typ == 0) {
        [FileDownloadTool alert:@"内容不能为空！" view:self.view];
        return;
    }
    
    [self.routeTaskView.innerView removeFromSuperview];
    [self.routeTaskView removeFromSuperview];
    
    //3.判断当前位置是否在地图内,不在的话直接返回
    if (typ ==1) {
        BOOL isIn = [FMDataBaseTool whetherInMapPolygon:start];
        if (!isIn) {
            [FileDownloadTool alert:@"对不起，您不在景区范围内" view:self.view];
            self.isTapRouting = NO;
            return;
        }
    }
    self.numStops = 0;
    //1.添加起点和终点
    [self addStop:start type:1];
    if(self.routeTaskParams){
        self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
    }
    
    if (self.isTapRouting) {
       [self addStop:end type:2];
        if(self.graphicsLayerStops.graphics.count>1){
            [self solveRoute];
        }
        if(self.routeTaskParams){
            self.routeTaskParams.outSpatialReference = self.mapView.spatialReference;
        }
    }
    
}


#pragma mark --创建用于显示路径规划线路的图层(路径规划)
-(AGSGraphicsLayer *)routeTaskResultLayer
{
    AGSSimpleLineSymbol *sls = [AGSSimpleLineSymbol simpleLineSymbol];
    sls.color = [UIColor blueColor];
    sls.style = AGSSimpleLineSymbolStyleSolid;
    sls.width = 4;
    AGSGraphicsLayer *graphicsLayerRoute = [AGSGraphicsLayer graphicsLayer];
    graphicsLayerRoute.renderer = [AGSSimpleRenderer simpleRendererWithSymbol:sls];
    return graphicsLayerRoute;
}

*/


#pragma mark -地图离线包下载(需要先弹框，确认是否下载)
-(void)downloadOfflineMapFiles
{
    //弹出下载进度框
        UIAlertController *alertview=[UIAlertController alertControllerWithTitle:@"下载离线包进度" message:nil preferredStyle:UIAlertControllerStyleAlert];
        _downloadProgressV = [[UIProgressView alloc]initWithFrame:CGRectMake(30, 50,160, 40)];
        _downloadProgressV.progress= 0.0;
        [alertview.view addSubview:_downloadProgressV];
        _downloadProgressLab = [[UILabel alloc]initWithFrame:CGRectMake(210, 30, 70, 40)];
        _downloadProgressLab.textColor = [UIColor blueColor];
        _downloadProgressLab.font = [UIFont systemFontOfSize:14];
        [alertview.view addSubview:_downloadProgressLab];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            WS(ws);
            [ws.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                _downloadProgressV = nil;
                ws.downloadTask = nil;
                ws.session = nil;
                 ws.downloadFlag = 20;
            }];
           
        }];
        [alertview addAction:cancel];
    
        [self presentViewController:alertview animated:YES completion:nil];

}

#pragma mark -开始下载地图离线包
- (void)downZipFromServer{
    
    NSURL *URL = [NSURL URLWithString:downloadUrl];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //下载Task操作
    _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // @property int64_t totalUnitCount;  需要下载文件的总大小
        // @property int64_t completedUnitCount; 当前已经下载的大小
        
        // 给Progress添加监听 KVO
        NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
         NSLog(@"total = %lld",downloadProgress.totalUnitCount);
        _tmpTotal = downloadProgress.totalUnitCount;
        if (downloadProgress.totalUnitCount == _total) {
            _downloadFlag = 200;//表示已经下载过离线包
            WS(ws);
            [ws.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                ws.downloadTask = nil;
                ws.session = nil;
            }];
            return;
        }
        // 回到主队列刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!_downloadProgressV) {
                [self downloadOfflineMapFiles];
            }
            self.downloadProgressV.progress =1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            double percent= self.downloadProgressV.progress *100;
            NSString *percentStr = [NSString stringWithFormat:@"%0.2f %%",percent];
            _downloadProgressLab.text =percentStr;
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        //删除zip包
        [FileDownloadTool delZipFiles];
      
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
        if (error) {
            //处理网络异常中断，与服务器断开链接的状况
            if (_downloadFlag == 200) {
                [FileDownloadTool alert:@"您已下载离线地图包" view:self.view];
            }else
            {
                MapInfo *info = [MapInfo shareMapInfo];

                if (_downloadFlag!=20 && info.internetStatus == 2) {
                    [self dismissViewControllerAnimated:NO completion:nil];
                }
                [FileDownloadTool alert:@"下载异常，中断" view:self.view];
                
            }
            
            return;
        }
        
        
        WS(ws);
       
        [ws dismissViewControllerAnimated:NO completion:nil];
        _total = _tmpTotal;
        [FileDownloadTool alert:@"下载离线包完成" view:ws.view];
        NSString *imgFilePath = [filePath path];// 将NSURL转成NSString
        [FileDownloadTool OpenZip:imgFilePath unzipto:cachesPath];
        NSLog(@"success=%@",imgFilePath);
    }];
    
    [_downloadTask resume];
}


#pragma mark-单个文件的大小
-(long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


#pragma mark -AGSLocationDisplayDatasourceDelegate
-(void)locationDisplayDataSource:(id<AGSLocationDisplayDataSource>)dataSource didUpdateWithHeading:(double)heading
{
    CGAffineTransform transform = CGAffineTransformMakeRotation(-1*degreesToRadians(heading));
    self.compassBtn.transform = transform;
    self.mapView.rotationAngle=heading;
}

-(void)locationDisplayDataSource:(id<AGSLocationDisplayDataSource>)dataSource didFailWithError:(NSError *)error
{
    
}

-(void)locationDisplayDataSource:(id<AGSLocationDisplayDataSource>)dataSource didUpdateWithLocation:(AGSLocation *)location
{
    
}

-(void)locationDisplayDataSourceStarted:(id<AGSLocationDisplayDataSource>)dataSource
{
    
}

-(void)locationDisplayDataSourceStopped:(id<AGSLocationDisplayDataSource>)dataSource
{
    
}



//使用KVC取值, 没有找到对应的key
- (id)valueForUndefinedKey:(NSString *)key {
    //    NSLog(@"不能识别%@", key);
    return nil;
}

#pragma mark - KVC
//使用KVC赋值, 没有找到对应的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    //NSLog(@"不能识别%@", key);
    
}

#pragma mark -内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 视图移除操作
-(void)removeAllViews
{
    [self.markCollectionView removeFromSuperview];
    [self.bottomView removeFromSuperview];
    [self.resultTable removeFromSuperview];
    [self.mapView removeMapLayer:_baseMarkLayer];
    [self.mapView removeMapLayer:_entryMarkLayer];
    [self.mapView removeMapLayer:_markLayer];
    [self.mapView removeMapLayerWithName:@"baseMarkLayer"];
    [self.mapView removeMapLayer:_ridingFeatureTableLayer];
    [self.mapView removeMapLayer:_youbuFeatureTableLayer];
    [self.mapView removeMapLayerWithName:@"youbuBase"];
    [self.mapView removeMapLayerWithName:@"TiledMapLayer"];
    [self.mapView removeFromSuperview];
    NSLog(@"333");
    if(self.mapView.locationDisplay.dataSourceStarted){
        [self.mapView.locationDisplay stopDataSource];
        self.mapView.rotationAngle = 0;
        
    }
    self.originalEnvelope = nil;
    self.normalImgArr = nil;
    self.selectImgArr = nil;
    self.routeLayer = nil;
    self.markLabelNameArr = nil;
    self.markLayer = nil;
    self.baseMarkLayer = nil;
    self.entryMarkLayer = nil;
    self.searchView = nil;
    self.resultTable = nil;
    self.ridingFeatureTableLayer = nil;
    self.youbuFeatureTableLayer = nil;
    self.searchResultModelArr = nil;
    self.searchResultGraphicArr = nil;
    
    self.mapView = nil;
    self.bottomView= nil;
    self.markCollectionView = nil;
    self.downloadTask = nil;
    self.compassBtn = nil;
    self.downloadBtn = nil;
}

#pragma mark -视图移除
- (void)viewDidUnload {
    //Stop the GPS, undo the map rotation (if any)
    [self removeAllViews];
}

-(void)dealloc
{
     [self removeAllViews];
}

@end
