上一章有一些地理編碼 反地理編碼的理論知識嫌套,有興趣的話可以去了解一下
下面是代碼示例:
//
// ViewController.m
// 地理編碼 反地理編碼
//
// Created by scsys on 16/3/8.
// Copyright ? 2016年 安靜SRR. All rights reserved.
//
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1掠抬、地理編碼:把地名轉(zhuǎn)換成位置信息 用處:把文字描述的位置轉(zhuǎn)換成地圖上的經(jīng)緯度
//2绊率、反地理編碼:把位置信息轉(zhuǎn)換成文字 用處:可以通過點擊選擇地圖上的某一位置來獲得這一位置文字的描述
//地理編解碼 在編解碼的時候是一個耗時的操作 可以使用異步操作
CLGeocoder *geocode = [[CLGeocoder alloc]init];
[geocode geocodeAddressString:@"童話王國" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *placemark = placemarks.firstObject;
CLLocation *loc = placemark.location;
NSLog(@"經(jīng)度%f緯度%f",loc.coordinate.latitude,loc.coordinate.longitude);
//CLRegion:方圓 范圍
// CLCircularRegion:是CLRegion的子類表示圓形一個范圍
CLLocationCoordinate2D coordinate ;
coordinate.latitude = 34;
coordinate.longitude = 113;
CLCircularRegion *region = [[CLCircularRegion alloc]initWithCenter:coordinate radius:kCLLocationAccuracyBest identifier:@"ll"];
[geocode geocodeAddressString:@"童話王國" inRegion:region completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *placemark = placemarks.firstObject;
CLLocation *loc = placemark.location;
NSLog(@"經(jīng)度%f緯度%f",loc.coordinate.latitude,loc.coordinate.longitude);
}];
NSLog(@"%@",[placemark.addressDictionary[@"FormattedAddressLines"] firstObject]);
}];
/*
使用GCD的異步操作來處理這個耗時的操作趋惨,防止阻塞主線程
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[geocode geocodeAddressString:@"童話王國" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLLocation *loc = placemarks.firstObject.location;
NSLog(@"經(jīng)度%f緯度%f",loc.coordinate.latitude,loc.coordinate.longitude);
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_sync(main, ^{
//更新UI 要在主線程更新UI
});
}];
});*/
//反地理編碼:把經(jīng)緯度轉(zhuǎn)換成地名
CLLocation *loc = [[CLLocation alloc]initWithLatitude:34.707 longitude:113.509];
[geocode reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
/*
placemarks這個數(shù)組里面只有一個元素,可以通過這個元素獲得以下信息:
<1>location:位置信息
<2>region:范圍
<3>addressDictionary:地址信息字典
1评矩、name:地名
2饺藤、thoroughfare:街道
3、subThoroughfare:街道的副標(biāo)題
4干旧、locality:城市
5渠欺、subLocality:城市的相關(guān)信息
6、administrativeArea:州 省
7椎眯、subAdministrativeArea:州省相關(guān)信息
8挠将、postalCode:郵政編碼
9胳岂、ISOcountryCode:國家編碼
10、country:國家
11舔稀、inlandWater:水源 湖泊
12乳丰、ocean:海洋
13、areasOfInterest:相關(guān)的地標(biāo)
*/
NSLog(@"%@",placemarks.firstObject.name);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end