標籤:
我們平時做地圖定位,主要是靠經緯度來準確定位某個位置。
但是,我們是人啊,我們不是衛星啊。
使用者在地圖上查一個地方,我們總不能告訴他,這個地方是東經多少度,北緯多少度吧。
咱們好歹得告訴人家個地名不是?
這就是我們今天說的地理編碼和地理反編碼。
地理編碼:你說個地名,比如“西湖”,我們給你返回它的經緯度,然後你通過查出來的這個經緯度去定位
反地理編碼:我告訴你一個經緯度,你通過經度緯度返回地名。最好在插個圖釘在地圖上就更好了,啥叫圖釘,咱們以後再說。
首先,我的介面是這個樣紙的,就是兩個按鈕,拖線,產生兩個方法
原始碼如下
//
// ViewController.m
// Demo3_反地理編碼
//
// Created by shiran on 16/3/23.
// Copyright © 2016年 shiran. All rights reserved.
//
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
//地理編碼
@property(nonatomic,strong)CLGeocoder *geocoder;
@end
@implementation ViewController
-(CLGeocoder *)geocoder{
if (!_geocoder) {
_geocoder=[[CLGeocoder alloc]init];
}
return _geocoder;
}
//地理編碼
- (IBAction)geocoder:(UIButton *)sender {
NSString *address=@"西湖";
if (address.length==0) {
return;
}
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error==nil) {
for (CLPlacemark *placeMark in placemarks) {
NSLog(@"%@",placeMark.addressDictionary[@"City"]);
NSLog(@"%f,%f",placeMark.location.coordinate.latitude,placeMark.location.coordinate.longitude);
}
}
else
{
NSLog(@"%@",error);
}
}];
}
//反地理編碼
- (IBAction)reverseGeocoder:(UIButton *)sender {
CLLocation *loc = [[CLLocation alloc]initWithLatitude:40 longitude:116];
[self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error==nil) {
for (CLPlacemark *placemark in placemarks) {
NSLog(@"%@,%@",placemark.addressDictionary[@"City"],placemark.name);
}
}
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
點擊 地理編碼 按鈕,控制台輸出如下 ,因為我的模擬器是英文的,所以控制台列印也是英文的,就這麼洋氣^_^
看,南昌的經緯度和杭州的經緯度都出來了,看來不止杭州有個西湖,南昌也有西湖啊,長姿勢吧^_^
點擊 反地理編碼 按鈕,控制台輸出如下
這裡,根據我的經緯度返回的地址是北京門頭溝
objective-c開發——地圖定位之地理編碼和地理反編碼