关于根据地址返回经纬度(1)

这两天做了一个关于定位的需求,此时做一下记录。

对于需求的解析:

需求:需要根据用户输入的地址返回经纬度,可以在地图上选择点,细微修改。

① 用户输入地址,可以模糊查询。

② 选择模糊查询地址,可以在地图上定点,并且用户点击可以改变定点。

方法:

① 使用高德的地图SDK以及搜索SDK

② 在录入数据页面点击地图按钮,创建一个地图,在地图上显示选中的地址视图;

③ 点击视图,跳转到搜索控制器,选择模糊查询地址返回地图控制器,并返回选中的地址;

④ 在地图控制器更新选中的地址,并且更新地址视图;

⑤ 点击返回定位,返回录入数据页面并返回经纬度及地址。

地图控制器实现:

typedef void(^SelectedTipCallback)(NSDictionary * _Nullable dataDict);
@interface TipViewController : UIViewController<RMHttpDelegate>
@property(nonatomic,copy)SelectedTipCallback selectedTipCallBack;
@end

#import "TipViewController.h"
#import "AMapTipAnnotation.h"
#import "SearchTipsViewController.h"
#import "ReGeocodeAnnotation.h"

@interface TipViewController ()<MAMapViewDelegate,AMapSearchDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) MAPointAnnotation *poiAnnotation;
@property (nonatomic, strong) AMapTipAnnotation *tipAnnotation;
@property (nonatomic, strong) UILabel *addressLbl;
@property (nonatomic, strong) NSMutableDictionary *addressDic;
//地图
@end

@implementation TipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = kBackGroudColor;
    self.title = @"获取经纬度";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = NO;
    
    [self navigationItemInit];
    //创建地图
    ///地图需要v4.5.0及以上版本才必须要打开此选项(v4.5.0以下版本,需要手动配置info.plist)
    [AMapServices sharedServices].enableHTTPS = YES;
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    // 自动调整view的宽度,保证左边距和右边距不变
    // 自动调整view与父视图上边距,以保证下边距不变
    self.mapView.autoresizingMask =
    UIViewAutoresizingFlexibleWidth |
    UIViewAutoresizingFlexibleHeight;
    //地图比例
    self.mapView.zoomLevel = 14;
    //可以点击
    self.mapView.touchPOIEnabled = YES;
    self.mapView.delegate = self;
    // 开启当前定位
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self.view addSubview:self.mapView];
    
    UIView *addressView = [[UIView alloc] init];
    addressView.backgroundColor = kBackGroudColor;
    addressView.layer.masksToBounds = YES;
    addressView.layer.cornerRadius = 15;
    [self.view addSubview:addressView];
    [addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.left.mas_equalTo(30);
        make.height.mas_equalTo(80);
        make.top.mas_equalTo(20);
    }];
    
    self.addressLbl = [UILabel labelWithFrame:CGRectMake(5, 5, kFit(ScreenWidth-70), kFit(70)) text:@"" textColor:UIColorFromHex(0X666666) fontSize:kFit(15) textAlignment:NSTextAlignmentLeft];
    self.addressLbl.numberOfLines = 0;
    [addressView addSubview:self.addressLbl];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAdress)];
    [addressView addGestureRecognizer:tap];
    
    //搜索,用户逆编码
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
   
    self.addressDic = [NSMutableDictionary dictionaryWithCapacity:0];
}

#pragma mark - Initialization
//导航栏
- (void)navigationItemInit {
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 44)];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"back-nav"] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc ] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:@selector(back)];
    negativeSpacer.width = -5;
    
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, item, nil];
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 44)];
    [btn2 addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
    [btn2 setTitle:@"返回定位" forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:btn2];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark - action
//跳转到搜索控制器
- (void)selectAdress{
    __weak typeof(self)weakSelf = self;
    //搜索控制器
    SearchTipsViewController *searchTipsVC = [[SearchTipsViewController alloc] init];
    searchTipsVC.searchTipCallBack = ^(AMapTip * _Nonnull aMapTip) {
        [weakSelf clearAndShowAnnotationWithTip:aMapTip];
        weakSelf.addressLbl.text = aMapTip.address;
        weakSelf.poiAnnotation =nil;
        [weakSelf.addressDic setValue:[NSString stringWithFormat:@"%f",aMapTip.location.latitude] forKey:@"latitude"];
        [weakSelf.addressDic setValue:[NSString stringWithFormat:@"%f",aMapTip.location.longitude] forKey:@"longitude"];
        //获取逆编码地址
        AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
        regeo.location                    = [AMapGeoPoint locationWithLatitude:aMapTip.location.latitude longitude:aMapTip.location.longitude];
        regeo.requireExtension            = YES;
        
        [self.search AMapReGoecodeSearch:regeo];
    };
    [self.navigationController pushViewController:searchTipsVC animated:YES];
}

//根据经纬度逆编码
- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location                    = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension            = YES;
    [self.search AMapReGoecodeSearch:regeo];
}
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}
//返回定位
-(void)confirm{
    if (self.selectedTipCallBack) {
        self.selectedTipCallBack(self.addressDic?:nil);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - AMapSearchDelegate
//报错
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    self.addressLbl.text = response.regeocode.formattedAddress;
    [self.addressDic setValue:response.regeocode.formattedAddress forKey:@"address"];
    
}

#pragma mark - MAMapViewDelegate
//在后台开启定位,需要实现这个方法
- (void)mapViewRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}
/**
 * @brief 地图初始化完成(在此之后,可以进行坐标计算)
 * @param mapView 地图View
 */
- (void)mapInitComplete:(MAMapView *)mapView{
    [self searchReGeocodeWithCoordinate:mapView.centerCoordinate];
    [self.addressDic setValue:[NSString stringWithFormat:@"%f",mapView.centerCoordinate.latitude] forKey:@"latitude"];
    [self.addressDic setValue:[NSString stringWithFormat:@"%f",mapView.centerCoordinate.longitude] forKey:@"longitude"];
}
//地图上的蓝点或者是小钉子-annotation
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *touchPoiReuseIndetifier = @"touchPoiReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:touchPoiReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:touchPoiReuseIndetifier];
        }
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop   = NO;
        annotationView.draggable      = NO;
        return annotationView;
    }
    
    return nil;
}

//单击地图使用该回调获取POI信息
- (void)mapView:(MAMapView *)mapView didTouchPois:(NSArray *)pois
{
    if (pois.count == 0)
    {
        return;
    }
    
    MAPointAnnotation *annotation = [self annotationForTouchPoi:pois[0]];
    /* 清除annotations & overlays */
    [self clear];
    /* Remove prior annotation. */
    [self.mapView removeAnnotation:self.poiAnnotation];
    
    [self.mapView addAnnotation:annotation];
    [self.mapView selectAnnotation:annotation animated:YES];
    
    self.poiAnnotation = annotation;
    self.tipAnnotation = nil;
    
    [self searchReGeocodeWithCoordinate:annotation.coordinate];
    [self.addressDic setValue:[NSString stringWithFormat:@"%f",annotation.coordinate.latitude] forKey:@"latitude"];
    [self.addressDic setValue:[NSString stringWithFormat:@"%f",annotation.coordinate.longitude] forKey:@"longitude"];
}

//根据点击创建Annotation
/* Convert MATouchPoi to MAPointAnnotation. */
- (MAPointAnnotation *)annotationForTouchPoi:(MATouchPoi *)touchPoi
{
    if (touchPoi == nil)
    {
        return nil;
    }
    
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    
    annotation.coordinate = touchPoi.coordinate;
    annotation.title      = touchPoi.name;
    
    return annotation;
}



#pragma mark - 地图处理
/* 清除annotations & overlays */
- (void)clear
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeAnnotation:self.mapView.userLocation];
    [self.mapView removeOverlays:self.mapView.overlays];
}

//清除当前的点以及更新搜索出来的点
- (void)clearAndShowAnnotationWithTip:(AMapTip *)tip
{
    /* 清除annotations & overlays */
    [self clear];
    
    if (tip.uid != nil && tip.location != nil) /* 可以直接在地图打点  */
    {
        AMapTipAnnotation *annotation = [[AMapTipAnnotation alloc] initWithMapTip:tip];
        
        self.tipAnnotation = annotation;
        [self.mapView addAnnotation:annotation];
        [self.mapView setCenterCoordinate:annotation.coordinate];
        [self.mapView selectAnnotation:annotation animated:YES];
    }
}

/*
#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.
}
*/

@end
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容