You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

442 lines
16 KiB

//
// RailAddressViewController.m
// watch
//
// Created by xTT on 2017/7/13.
// Copyright © 2017xTT. All rights reserved.
//
#import "RailAddressViewController.h"
#import "RailSearchAddressVC.h"
#import "CLLocation+YCLocation.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "RailAddressTableViewCell.h"
#define SearchHistroySaveCount 5
@interface RailAddressViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate,CLLocationManagerDelegate,AMapSearchDelegate,UISearchBarDelegate>
@property (nonatomic, strong) CLLocation *curLocation;
@property (nonatomic, strong) MKCircle *mapCircle;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) AMapInputTipsSearchRequest *currentRequest;
/**
历史搜索数据
*/
@property (nonatomic, strong) NSMutableArray *historyData;
/**
是否是历史记录的模式
*/
@property (nonatomic, assign) BOOL isHistory;
@end
@implementation RailAddressViewController
@synthesize myDataSource = _myDataSource;
- (NSMutableArray *)myDataSource{
if (!_myDataSource) {
_myDataSource = [NSMutableArray array] ;
}
return _myDataSource;
}
- (Rail *)infoRail{
if (!_infoRail) {
_infoRail = [[Rail alloc] init];
}
return _infoRail;
}
- (CLLocation *)curLocation{
if (!_curLocation) {
if (self.infoRail.id) {
_curLocation = [[CLLocation alloc] initWithLatitude:[self.infoRail.lat doubleValue]
longitude:[self.infoRail.lon doubleValue]];
}else if(cUser.cDevice.lastLocation){
_curLocation = [[CLLocation alloc] initWithLatitude:cUser.cDevice.lastLocation.lat.doubleValue
longitude:cUser.cDevice.lastLocation.lon.doubleValue];
}else if(cUser.curLocation){
_curLocation = [[CLLocation alloc] initWithLatitude:[cUser.curLocation locationMarsFromEarth].coordinate.latitude
longitude:[cUser.curLocation locationMarsFromEarth].coordinate.longitude];
}
}
return _curLocation;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.zx_navTitle = @"地址";
[self zx_setRightBtnWithText:@"保存" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
[self rightBarItemClick];
}];
[self.zx_navRightBtn setTitleColor:mainColor forState:0];
self.searchBar.delegate = self;
if(self.infoRail.address){
self.searchBar.text = self.infoRail.address;
}else{
LGAlertView *alertView = [[LGAlertView alloc] initWithTitle:@"提示" message:@"请长按地图选择地址" style:LGAlertViewStyleAlert buttonTitles:@[@"确定"] cancelButtonTitle:nil destructiveButtonTitle:nil actionHandler:^(LGAlertView *alertView, NSString *title, NSUInteger index) {
} cancelHandler:nil destructiveHandler:nil];
[alertView showAnimated:YES completionHandler:nil];
}
//初始化搜索
self.search = [[AMapSearchAPI alloc] init];
self.search.delegate = self;
// 走过的进度条的颜色
self.sliderView.minimumTrackTintColor = mainColor;
// 通常状态下
[self.sliderView setThumbImage:[UIImage imageNamed:@"icon_sliding"] forState:UIControlStateNormal];
// 滑动状态下
[self.sliderView setThumbImage:[UIImage imageNamed:@"icon_sliding"] forState:UIControlStateHighlighted];
self.sliderView.maximumValue = 1000;
self.sliderView.minimumValue = 300;
if(self.infoRail.radius){
self.sliderView.value = [self.infoRail.radius floatValue];
}else{
self.infoRail.radius = @(500);
self.sliderView.value = 500.0;
}
self.railRangeLabel.text = [NSString stringWithFormat:@"%@米",self.infoRail.radius];
[self.sliderView addTarget:self action:@selector(sliderViewChangeAction:) forControlEvents:UIControlEventValueChanged];
[self.sliderView addTarget:self action:@selector(sliderViewChangeDidAction:) forControlEvents:UIControlEventTouchUpInside];
[self.myTableView registerNib:[UINib nibWithNibName:@"RailAddressTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"RailAddressTableViewCellID"];
//实例化长按手势监听
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] init];
[longPress addTarget:self action:@selector(handleMapViewLongPressed:)];
//代理
longPress.delegate = self;
longPress.minimumPressDuration = 1.0;
longPress.allowableMovement = 50.0;
//将长按手势添加到需要实现长按操作的视图里
[self.mapView addGestureRecognizer:longPress];
//定位一次自身的位置
//初始化管理器
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
//检查是否授权
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
}
-(void)sliderViewChangeAction:(UISlider*)slider{
int radiusInt = [NSNumber numberWithFloat:slider.value].intValue;
self.railRangeLabel.text = [NSString stringWithFormat:@"%d米",radiusInt];
}
-(void)sliderViewChangeDidAction:(UISlider*)slider{
[self.mapView removeOverlays:self.mapView.overlays];
int radiusInt = [NSNumber numberWithFloat:slider.value].intValue;
[slider setValue:radiusInt animated:YES];
MKCircle *mapCircle = [MKCircle circleWithCenterCoordinate:self.curLocation.coordinate
radius:radiusInt];
self.infoRail.radius = @(radiusInt);
self.railRangeLabel.text = [NSString stringWithFormat:@"%@米",self.infoRail.radius];
[self.mapView addOverlay:mapCircle];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self updateRegionWithAddress:NO];
// if (self.infoRail.id) {
// [self updateRegionWithAddress:YES];
// }else{
// [self updateRegionWithAddress:NO];
// }
}
//MARK: 封闭 侧滑手势
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
};
}
- (void)rightBarItemClick
{
if(self.searchBar.text.length == 0){
[UICommon MessageErrorText:@"请长按地图获取地址"];
}else{
[self.navigationController popViewControllerAnimated:YES];
}
// if (self.infoRail.name.length == 0) {
// [UICommon MessageErrorText:@"请输入地址名称"];
// }else if (!self.infoRail.lat || !self.infoRail.lon) {
// [UICommon MessageErrorText:@"请长按地图获取地址"];
// }else if ([self.infoRail.radius integerValue] < 300 || [self.infoRail.radius integerValue] > 1000) {
// [UICommon MessageErrorText:@"安全范围为300~1000米"];
// }else{
// [self.infoRail saveSuccess:^{
// [self goBack:nil];
// } failure:^{}];
// }
}
//长按事件的实现方法
- (void)handleMapViewLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
NSLog(@"UIGestureRecognizerStateBegan");
CGPoint pt = [gestureRecognizer locationInView:_mapView];
CLLocationCoordinate2D coordinate = [_mapView convertPoint:pt toCoordinateFromView:_mapView];
self.curLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude
longitude:coordinate.longitude];
//23.123625574141336 113.39765354990959
// self.curLocation = [[CLLocation alloc] initWithLatitude:23.123625574141336
// longitude:113.39765354990959];
// _watchLocation = CLLocationCoordinate2DMake(latitude, longitude);
[self updateRegionWithAddress:YES];
} else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
NSLog(@"UIGestureRecognizerStateChanged");
} else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSLog(@"UIGestureRecognizerStateEnded");
}
}
/**
更新区域的
@param getAddress 是否更新 搜索栏的 地址信息
*/
- (void)updateRegionWithAddress:(BOOL)getAddress;
{
if (self.curLocation) {
[self.mapView removeOverlays:self.mapView.overlays];
[self.mapView removeAnnotations:self.mapView.annotations];
int radius = 500;
if (self.infoRail.radius) {
radius = [self.infoRail.radius intValue];
}
MKCircle *mapCircle = [MKCircle circleWithCenterCoordinate:self.curLocation.coordinate
radius:radius];
[self.mapView addOverlay:mapCircle];
MKPointAnnotation *locateAnnotation = [[MKPointAnnotation alloc] init];
locateAnnotation.coordinate = self.curLocation.coordinate;
@try {
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(self.curLocation.coordinate, radius * 3, radius * 3)
animated:YES];
} @catch (NSException *exception) {
xLog(@"radius :%d coordinate: lon:%f lat: %f",radius ,self.curLocation.coordinate.longitude,self.curLocation.coordinate.latitude);
} @finally {
}
[self.mapView addAnnotation:locateAnnotation];
if (getAddress) {
[self getAddressWithLocation:self.curLocation];
}
}
}
#pragma mark 根据坐标取得地名
-(void)getAddressWithLocation:(CLLocation *)location{
//反地理编码
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
WEAKSELF
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks firstObject];
NSLog(@"详细信息:%@",placemark.addressDictionary);
// NSString *state = placemark.locality;
// if (!state) {
// //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
// state = placemark.administrativeArea;
// }
NSString *name;
if(placemark.subLocality){
name = [NSString stringWithFormat:@"%@ %@",
placemark.subLocality,placemark.name];
}else{
name = [NSString stringWithFormat:@"%@ %@",
placemark.locality,placemark.name];
}
if (placemark.name) {
weakSelf.infoRail.address = name;
[weakSelf.infoRail setValue:name forKey:@"address"];
//在导航栏上赋值地址
weakSelf.searchBar.text = name;
}
weakSelf.infoRail.lon = @(location.coordinate.longitude);
weakSelf.infoRail.lat = @(location.coordinate.latitude);
[weakSelf.myTableView reloadData];
}];
}
#pragma mark MKMapViewDelegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
NSLog(@"重新渲染 rendererForOverlay");
if ([overlay isKindOfClass:[MKCircle class]]) {
MKCircleRenderer *circleRenderer = [[MKCircleRenderer alloc] initWithCircle:overlay];
circleRenderer.lineWidth = 1.0f;
circleRenderer.strokeColor = mainColor;
circleRenderer.fillColor = [mainColor colorWithAlphaComponent:0.2];
return circleRenderer;
}
return nil;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
static NSString *customReuseIndetifier = @"customReuseIndetifier";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
if (annotationView == nil) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
// must set to NO, so we can show the custom callout view.
annotationView.canShowCallout = NO;//允许交互点击
annotationView.draggable = NO;
}
annotationView.image = [myHelper getImageWithName:@"module_location_icon"];//设置大头针视图的图片
annotationView.selected = YES;
return annotationView;
}
return nil;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if ([self.infoRail.radius integerValue] < 300 || [self.infoRail.radius integerValue] > 1000) {
[UICommon MessageErrorText:@"安全范围为300~1000米"];
}else{
[self updateRegionWithAddress:YES];
}
return YES;
}
//MARK: 定位管理器的 代理
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusNotDetermined:
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
break;
default:
break;
}
}
//MARK : 初始化 用户位置
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *userLocation = [locations lastObject];
[User currentUser].curLocation = userLocation; //设置用户信息
[manager stopUpdatingLocation];
//如果没有 电子围栏 curLocation 为用户位置
if(!self.infoRail.id){
if(!cUser.cDevice.lastLocation){
self.curLocation = [userLocation locationMarsFromEarth]; //转换用户位置为火星坐标
}
// [self updateRegionWithAddress:NO];
}
}
//MARK: -----搜索框 UISearchBarDelegate -----
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
xLog(@"searchBarCancelButtonClicked");
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
WEAKSELF
//跳转到新的页面
RailSearchAddressVC * vc = [RailSearchAddressVC new];
vc.selectAddressCallBack = ^(NSString *searchResult, AMapGeoPoint *point) {
weakSelf.curLocation = [[CLLocation alloc] initWithLatitude:point.latitude
longitude:point.longitude];
[weakSelf updateRegionWithAddress:YES];
weakSelf.searchBar.text = searchResult;
};
[self.navigationController pushViewController:vc animated:YES];
return NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
switch (self.mapView.mapType) {
case MKMapTypeHybrid:
{
self.mapView.mapType = MKMapTypeStandard;
}
break;
case MKMapTypeStandard:
{
self.mapView.mapType = MKMapTypeHybrid;
}
break;
default:
break;
}
self.mapView.mapType = MKMapTypeStandard;
// Dispose of any resources that can be recreated.
}
@end