单军华
2018-07-12 3e8437ae559487362fae3525beb79c534c213a51
screendisplay/screendisplay/Classes/??/Controller/MonitoringMapViewController.m
New file
@@ -0,0 +1,647 @@
//
//  MonitoringMapViewController.m
//  screendisplay
//
//  Created by 单军华 on 2018/7/5.
//  Copyright © 2018年 单军华. All rights reserved.
//
#import "MonitoringMapViewController.h"
#import "MyAnimatedAnnotationView.h"
#import "DevicesService.h"
#import "DeviceModel.h"
#import "NSObject+CustomIndex.h"
#import "DetailDataViewController.h"
#import "AppDelegate.h"
@interface MonitoringMapViewController ()
{
    BMKPointAnnotation* pointAnnotation;
    BMKPointAnnotation* animatedAnnotation;
    BMKPointAnnotation* lockedScreenAnnotation;
    UIView * popView;
    BMKPinAnnotationView *annotationView;
    BMKActionPaopaoView * pPaopaoView;
    UILabel * titleLabel;
    UILabel * addressLabel;
    NSTimer * myTimer; // 更新设备状态
    int  hCurrentIndex;
}
/** digest */
@property (nonatomic, strong) DevicesService *deviceSevice;
@end
@implementation MonitoringMapViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 禁用右滑返回
    self.fd_interactivePopDisabled = YES;
    //[self setNavBarImg:@"map_top_bar_bk"];
    [self initMap];
    [self getDevicesList:FALSE];
    //每1秒运行一次function方法。
    myTimer =  [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(updateDevices) userInfo:nil repeats:YES];
    hCurrentIndex = 0;
    //[self addMapMark];
}
-(void) initMap
{
#pragma mark baidumap init begin
    //适配ios7
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
    {
        //        self.edgesForExtendedLayout=UIRectEdgeNone;
        self.navigationController.navigationBar.translucent = NO;
    }
    self.view.backgroundColor = kUIColorFromRGB(0x0b2f76);
    UIImageView * viewBackground = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-AdaptedWidth(355))/2, NavBar_Height+AdaptedHeight(13), AdaptedWidth(355), AdaptedHeight(576))];
    viewBackground.image = [UIImage imageNamed:@"map_background"];
    [self.view addSubview:viewBackground];
    //初始化地图
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-AdaptedWidth(350))/2, NavBar_Height+AdaptedHeight(16), AdaptedWidth(350), AdaptedHeight(570))];
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.showMapScaleBar=YES;
    _mapView.mapType = BMKMapTypeStandard;
    [self.view addSubview:_mapView];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _coordinateXText = @"121.1379";
    _coordinateYText= @"31.466325";
    _cityText = @"太仓";
    _addrText = @"海淀区上地十街10号";
    [_mapView setZoomLevel:18]; //设置地图比例
#pragma mark baidumap init end
}
#pragma mark baidumap function begin
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    _geocodesearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    if (myTimer == nil)
        myTimer =  [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(updateDevices) userInfo:nil repeats:YES];
    else
        //开启定时器
        [myTimer setFireDate:[NSDate distantPast]];
}
-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时,置nil
    _geocodesearch.delegate = nil; // 不用时,置nil
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    //关闭定时器
    if(myTimer)
        [myTimer setFireDate:[NSDate distantFuture]];
}
- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}
- (void)dealloc {
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = _addrText;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString* titleStr;
        NSString* showmeg;
        titleStr = @"正向地理编码";
        showmeg = [NSString stringWithFormat:@"纬度:%f,经度:%f",item.coordinate.latitude,item.coordinate.longitude];
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
}
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0)
    {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = @"摩瑞尔电器有限公司";
        item.subtitle = [NSString stringWithFormat:@"地址:%@",result.address];
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        //LOG_INFO(@"反向地理编码");
    }
}
// 根据地址信息展示地图信息
-(void)onClickGeocode
{
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geocodeSearchOption.city= _cityText;
    geocodeSearchOption.address = _addrText;
    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
    }
}
// 根据经纬度展示地图信息
-(void)onClickReverseGeocode
{
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    if (_coordinateXText != nil && _coordinateYText != nil)
    {
        pt = (CLLocationCoordinate2D){[_coordinateYText floatValue], [_coordinateXText floatValue]};
    }
    BMKReverseGeoCodeSearchOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeocodeSearchOption.location = pt;
    reverseGeocodeSearchOption.isLatestAdmin = YES;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        //[self addMapMark];
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}
#pragma mark baidumap function end
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark Annotation function
 //添加标注
-(void)addMapMark
{
    //[_mapView removeOverlays:_mapView.overlays];
    [_mapView removeAnnotations:_mapView.annotations];
    [self addPointAnnotation];
    //[self addAnimatedAnnotation];
    //[self addLockScreenAnnotation];
}
//添加标注
-(void)addPointAnnotation
{
    for (int index = 0; index < self.deviceSevice.deviceViewModels.count; index++)
    {
        DeviceModel *pModel = [self.deviceSevice.deviceViewModels objectAtIndex:index];
        if(TWIsEmpty(pModel)) continue;
        BMKPointAnnotation * pPointAnno = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude = [pModel.latitude doubleValue];
        coor.longitude = [pModel.longitude doubleValue];
        pPointAnno.coordinate = coor;
        pPointAnno.title = pModel.device_name;
        pPointAnno.subtitle = pModel.address;
        pPointAnno.customIndex = [NSNumber numberWithInt:index];
        [_mapView addAnnotation:pPointAnno];
    }
}
//添加固定屏幕位置的标注
-(void)addLockScreenAnnotation
{
    if (lockedScreenAnnotation == nil) {
        lockedScreenAnnotation = [[BMKPointAnnotation alloc]init];
        lockedScreenAnnotation.isLockedToScreen = YES;
        lockedScreenAnnotation.screenPointToLock = CGPointMake(100, 100);
        lockedScreenAnnotation.title = @"我是固定屏幕的标注";
    }
    [_mapView addAnnotation:lockedScreenAnnotation];
}
// 添加动画Annotation
- (void)addAnimatedAnnotation {
    if (animatedAnnotation == nil) {
        animatedAnnotation = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude = 31.496381;
        coor.longitude = 121.190792;
        animatedAnnotation.coordinate = coor;
        animatedAnnotation.title = @"我是动画Annotation";
    }
    [_mapView addAnnotation:animatedAnnotation];
}
// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //动画annotation
    if (annotation == animatedAnnotation)
    {
        NSString *AnnotationViewID = @"AnimatedAnnotation";
        MyAnimatedAnnotationView *annotationView = nil;
        if (annotationView == nil) {
            annotationView = [[MyAnimatedAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        }
        NSMutableArray *images = [NSMutableArray array];
        for (int i = 1; i < 4; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"poi_%d.png", i]];
            [images addObject:image];
        }
        annotationView.annotationImages = images;
        return annotationView;
    }
    //普通annotation
    if ([annotation isKindOfClass:[BMKPointAnnotation class]])
    {
        NSString *AnnotationViewID = @"renameMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil)
        {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        }
        if (annotation == lockedScreenAnnotation)
        {
            // 设置颜色
            annotationView.pinColor = BMKPinAnnotationColorGreen;
            // 设置可拖拽
            annotationView.draggable = NO;
        }
        else
        {
            NSString * imageName = @"";
            DeviceModel *pModel = [self.deviceSevice.deviceViewModels objectAtIndex:[((BMKPointAnnotation*)annotation).customIndex intValue]];
            // 0 正常 1 一级警报 2 二级警报 3 三级警报 4 维保
            switch ([pModel.state intValue]) {
                case 0:
                {
                    imageName = @"map_segment_normal";
                }
                    break;
                case 1:
                {
                    imageName = @"map_segment_one";
                }
                    break;
                case 2:
                {
                    imageName = @"map_segment_two";
                }
                    break;
                case 3:
                {
                    imageName = @"map_segment_three";
                }
                    break;
                case 4:
                {
                    imageName = @"map_segment_four";
                }
                    break;
                default:
                    imageName = @"map_segment_four";
                    break;
            }
            //自定义标注的图像
            annotationView.image = [UIImage imageNamed:imageName];
            annotationView.size = CGSizeMake(32, 32);
            // 设置可拖拽
            annotationView.draggable = YES;
            //[annotationView setSelected:YES];
            annotationView.annotation = annotation;
            // 设定popView的高度
            CGFloat hWidth = 180;
            CGFloat hHight = 80;
            if(popView == nil)
            {
                popView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, AdaptedWidth(hWidth), AdaptedHeight(hHight))];
                //  自定义气泡中的button
                UIButton * popViewBk = [[UIButton alloc] initWithFrame:CGRectMake(5, 0, AdaptedWidth(hWidth), AdaptedHeight(hHight))];
                [popViewBk setBackgroundImage:[UIImage imageNamed:@"map_Airbubbles"] forState:UIControlStateNormal];
                [popViewBk addTarget:self action:@selector(clickPopView) forControlEvents:UIControlEventTouchUpInside];
                [popView addSubview:popViewBk];
                //  关闭按钮
                UIButton * coloseBtn = [[UIButton alloc]initWithFrame:CGRectMake(AdaptedWidth(hWidth-10-10), AdaptedHeight(10), AdaptedWidth(10), AdaptedHeight(10))];
                [coloseBtn setBackgroundImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
                [coloseBtn addTarget:self action:@selector(closePopView) forControlEvents:UIControlEventTouchUpInside];
                [popViewBk addSubview:coloseBtn];
                //  title
                if(titleLabel==nil)
                {
                    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(AdaptedWidth(10), AdaptedHeight(10), AdaptedWidth(hWidth-20-10), AdaptedHeight(20))];
                    titleLabel.font = AdaptedFontSize(10);
                    titleLabel.textColor = kUIColorFromRGB(0xff7800);
                    titleLabel.textAlignment = NSTextAlignmentLeft;
                    [popViewBk addSubview:titleLabel];
                }
                // 地址
                if(addressLabel==nil)
                {
                    addressLabel = [[UILabel alloc]initWithFrame:CGRectMake(AdaptedWidth(10), AdaptedHeight(10+20+2), AdaptedWidth(hWidth-20-10), AdaptedHeight(20))];
                    addressLabel.textColor = kUIColorFromRGB(0x595959);
                    addressLabel.textAlignment = NSTextAlignmentLeft;
                    addressLabel.font = AdaptedFontSize(10);
                    [popViewBk addSubview:addressLabel];
                }
                pPaopaoView = [[BMKActionPaopaoView alloc]initWithCustomView:popView];
                pPaopaoView.frame = CGRectMake(0, 0, AdaptedWidth(hWidth),  AdaptedHeight(hHight));
            }
            titleLabel.text = pModel.device_name;
            addressLabel.text = pModel.address;
            ((BMKPinAnnotationView *)annotationView).paopaoView = pPaopaoView;
            popView = ((BMKPinAnnotationView *)annotationView).paopaoView ;
        }
        // 从天上掉下效果
        annotationView.animatesDrop = NO;
        return annotationView;
    }
    return nil;
}
-(void)clickPopView
{
    DeviceModel* model = [self.deviceSevice.deviceViewModels objectAtIndex:hCurrentIndex];
    if([model.state intValue] == 4)
    {
        // Make toast with a title
        [self.navigationController.view makeToast:@"该设备维保中,不能获取实时数据!"
                                         duration:3.0
                                         position:CSToastPositionBottom
                                            title:@"温馨提示"
                                            image:nil
                                            style:nil
                                       completion:nil];
        //[MBProgressHUD showWarn:@"该设备维保中,不能获取实时数据!" ToView:self.view];
        //[Global alertMessageEx:@"该设备维保中,不能获取实时数据!" title:@"系统提示" okTtitle:nil cancelTitle:@"确定" delegate:self];
    }
    else
    {
        DetailDataViewController * page = [[DetailDataViewController alloc] init];
        //[self presentViewController:page animated:YES  completion:nil];
        page.deviceModel = [self.deviceSevice.deviceViewModels objectAtIndex:hCurrentIndex];
        [UserDefault setObject:page.deviceModel.mac forKey:@"mac"];
        [UserDefault setObject:page.deviceModel.state forKey:@"state"];
        [UserDefault synchronize];//使用synchronize强制立即将数据写入磁盘,防止在写完NSUserDefaults后程序退出导致的数据丢失
        [self.navigationController pushViewController:page animated:YES];
        NSLog(@"clickPopView");
    }
}
-(void)closePopView
{
    [annotationView setSelected:NO];
    [popView setHidden:YES];
    NSLog(@"closePopView");
}
// 当点击annotation view弹出的泡泡时,调用此接口
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
    NSLog(@"paopaoclick");
}
/**
 *当选中一个annotation views时,调用此接口
 *@param mapView 地图View
 *@param view 选中的annotation views
 */
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view;
{
    DeviceModel *pModel = [self.deviceSevice.deviceViewModels objectAtIndex:[((BMKPointAnnotation*)view.annotation).customIndex intValue]];
    titleLabel.text = pModel.device_name;
    addressLabel.text = pModel.address;
    hCurrentIndex = [((BMKPointAnnotation*)view.annotation).customIndex intValue];
    [popView setHidden:NO];
     NSLog(@"didSelectAnnotationView");
}
#pragma mark custom function
- (DevicesService *)deviceSevice
{
    if(_deviceSevice == nil) {
        _deviceSevice = [DevicesService new];
    }
    return _deviceSevice;
}
-(void)updateDevices
{
    [self getDevicesList:YES];
}
-(void)getDevicesList:(BOOL)bIsUpdate
{
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setObject:[UserDefault stringForKey:@"organizationId"] forKey:@"organizationId"];
    MBProgressHUD *HUD = nil;
    if(!bIsUpdate)
    {
        // 执行登录操作
        HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.labelText = @"数据加载中...";
        // 隐藏时候从父控件中移除
        HUD.removeFromSuperViewOnHide = YES;
        // YES代表需要蒙版效果
        HUD.dimBackground = YES;
    }
    TWWeak(self);
    [self.deviceSevice getDeviceListWithParameters:param completion:^(NSString *desc, int code) {
        if(!bIsUpdate)
            HUD.hidden = YES;
        if(code == 1)
        {
            if(weakself.deviceSevice.deviceViewModels.count > 0)
            {
                if(!bIsUpdate)
                {
                    DeviceModel * model = [weakself.deviceSevice.deviceViewModels objectAtIndex:0];
                    if(!TWIsEmpty(model))
                    {
                        _coordinateXText = model.longitude;
                        _coordinateYText = model.latitude;
                        [self onClickReverseGeocode];
                    }
                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                        [weakself addMapMark];
                    });
                }
                else
                {
                    [weakself addMapMark];
                }
            }
        }
        else
        {
            // Make toast with a title
            if(!bIsUpdate)
            {
                [Global alertMessageEx:desc title:@"获取设备失败" okTtitle:nil cancelTitle:@"OK" delegate:self];
            }
//            [self.navigationController.view makeToast:@"该设备维保中,不能获取实时数据!"
//                                             duration:3.0
//                                             position:CSToastPositionBottom
//                                                title:@"温馨提示"
//                                                image:nil
//                                                style:nil
//                                           completion:nil];
        }
    }];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - LMJNavUIBaseViewControllerDataSource
- (UIStatusBarStyle)navUIBaseViewControllerPreferStatusBarStyle:(LMJNavUIBaseViewController *)navUIBaseViewController
{
    return UIStatusBarStyleDefault;
}
/**头部标题*/
- (NSMutableAttributedString*)lmjNavigationBarTitle:(LMJNavigationBar *)navigationBar
{
     return [self changeTitle:@"监测地点" changeColor:[UIColor whiteColor]];
}
//背景图片
//- (UIImage *)lmjNavigationBarBackgroundImage:(LMJNavigationBar *)navigationBar
//{
//    return [UIImage imageNamed:@"map_top_bar_bk"];
//}
/** 背景色 */
- (UIColor *)lmjNavigationBackgroundColor:(LMJNavigationBar *)navigationBar
{
    return kUIColorFromRGB(0x0b2f76);
}
/** 是否隐藏底部黑线 */
- (BOOL)lmjNavigationIsHideBottomLine:(LMJNavigationBar *)navigationBar
{
    return YES;
}
/** 导航条左边的按钮 */
- (UIImage *)lmjNavigationBarLeftButtonImage:(UIButton *)leftButton navigationBar:(LMJNavigationBar *)navigationBar
{
    return nil;
    //return [UIImage imageNamed:@"map_back"];
}
/** 导航条右边的按钮 */
- (UIImage *)lmjNavigationBarRightButtonImage:(UIButton *)rightButton navigationBar:(LMJNavigationBar *)navigationBar
{
        [rightButton setTitle:@"退出登录" forState: UIControlStateNormal];
        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
        rightButton.lmj_width = 80;
    return nil;
}
#pragma mark - LMJNavUIBaseViewControllerDelegate
/** 左边的按钮的点击 */
-(void)leftButtonEvent:(UIButton *)sender navigationBar:(LMJNavigationBar *)navigationBar
{
    //[self onClickReverseGeocode];
    //[self dismissViewControllerAnimated:YES completion:nil];
}
/** 右边的按钮的点击 */
-(void)rightButtonEvent:(UIButton *)sender navigationBar:(LMJNavigationBar *)navigationBar
{
    [UserDefault setObject:@"0" forKey:@"isLogin"];
    [UserDefault setObject:nil forKey:@"user_id"];
    [GetAppDelegate showLoginPage];
    //[self addMapMark];
}
@end