地图篇-02.地理编码(GeoCoding/ReverseGeoCoding)
上一节给大家简单介绍了一下获取用户位置,用经纬度表示位置.这一节我们来讲讲地理编码.
首先,我们要知道什么是地理编码
概念:
地理编码:指的是将统计资料或是地址信息建立空间坐标关系的过程,称为地理编码.实现了将中文地址或地名描述转换为经纬度表示在地图上(地球表面上)功能。
反地理编码:实现了将地图上(地球表面上)的经纬度转换为中文地址或地名描述.
编码前准备:
在写代码之前,在storyboard中拖几个控件,如下图:
拖好这些控件之后,一定要记得初始化tabBarController,下图
完成以上步骤之后,我们就要开始写代码了
因为要将两个UIViewController显示在视图上,所以创建两个类,并且关联上
关联好了之后就把我们需要的控件,拖入到相应的类中
现在就可以开始写代码了(重点):
首先,导入头文件
#import <CoreLocation/CoreLocation.h>,上一小节中说过,这个头文件如果有很多类都要用到,可以写一个pch文件,这里简单说一下方法:
完成上一步你会发现CoreLocation在类中还是不能用,不要急,还有下一步:
上代码:
地理编码(GeoCoding):
1 //
2 // GeocodViewController.m
3 // 地理编码
4 //
5 // Created by admin on 16/5/21.
6 // Copyright © 2016年 KXZDJ. All rights reserved.
7 //
8
9 #import "GeocodViewController.h"
10
11 @interface GeocodViewController ()
12 @property (weak, nonatomic) IBOutlet UITextField *addressFiled;
13 @property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
14 @property (weak, nonatomic) IBOutlet UILabel *lontitudeLabel;
15 @property (weak, nonatomic) IBOutlet UITextView *detailTextView;
16
17 @end
18
19 @implementation GeocodViewController
20 - (IBAction)geoCode:(id)sender {
21
22 //创建地理编码对象
23 CLGeocoder *geo = [[CLGeocoder alloc] init];
24
25 //地理编码
26 [geo geocodeAddressString:self.addressFiled.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
27 //判断placemarks如果没有值或者error存在,就打印错误信息
28 if (placemarks.count == 0 || error) {
29 NSLog(@"%@",error);
30 return;
31 }
32
33 //获取地标
34 CLPlacemark *cpl = [placemarks lastObject];
35
36 //纬度
37 CLLocationDegrees latitude = cpl.location.coordinate.latitude;
38
39 //经度
40 CLLocationDegrees longtitude = cpl.location.coordinate.longitude;
41
42 //赋值(注意经纬度是double类型)
43 self.latitudeLabel.text = [NSString stringWithFormat:@"%f",latitude];
44 self.lontitudeLabel.text = [NSString stringWithFormat:@"%f",longtitude];
45
46 //定义一个临时字符串接收获取到的地址名字
47 NSString *tempStr = @"";
48
49 //遍历placemarks,获取当前坐标位置
50 for (CLPlacemark *cpl in placemarks) {
51 //这里为什么要追加字符串呢?因为placemarks是一个数组,里面有很多重名的地方(比如:上海有个南京路步行街,成都有个春熙路步行街,当用户输入步行街的时候,这两个都会显示出来,如果不追加的话,就只会显示一个)
52 tempStr = [tempStr stringByAppendingString:[NSString stringWithFormat:@"%@\n",cpl.name]];
53 }
54
55 //赋值给self.detailTextView
56 self.detailTextView.text = tempStr;
57
58
59 }];
60 }
61
62 - (void)viewDidLoad {
63 [super viewDidLoad];
64
65 }
66
67
68 @end
运行效果图:
现在大家应该理解placemarks和代码中拼接字符串的意义所在了.
反地理编码(ReverseGeoCoding):
1 //
2 // ReverseCodeViewController.m
3 // 地理编码
4 //
5 // Created by admin on 16/5/21.
6 // Copyright © 2016年 KXZDJ. All rights reserved.
7 //
8
9 #import "ReverseCodeViewController.h"
10
11
12 @interface ReverseCodeViewController ()
13 @property (weak, nonatomic) IBOutlet UITextField *latitudeLabel;
14 @property (weak, nonatomic) IBOutlet UITextField *longtitudeLabel;
15 @property (weak, nonatomic) IBOutlet UITextView *detailTextView;
16
17 @end
18
19 @implementation ReverseCodeViewController
20
21 - (void)viewDidLoad {
22 [super viewDidLoad];
23
2