iOS地图 -- 地理编码和反地理编码

地理编码和反地理编码

用到的类和方法

  • CLGeocoder --> 地理编码管理器
  • - (void)geocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler; --> 地理编码(将地址关键字 >> 经纬度)
  • - (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler; --> 反地理编码(将经纬度 >> 详细地址)
  • CLPlacemark --> 地标对象;包含对应的位置对象,地址名称,城市等等

地理编码和反地理编码的小练习

  • 简单布局

  • 练习代码
#import "ViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface ViewController ()

/** 地理编码管理器 */
@property (nonatomic, strong) CLGeocoder *geoC;

@property (weak, nonatomic) IBOutlet UITextView *addressTV;

@property (weak, nonatomic) IBOutlet UITextField *latitudeTF;

@property (weak, nonatomic) IBOutlet UITextField *longitudeTF;

@end

@implementation ViewController

#pragma mark - 懒加载
/** 地理编码管理器 */
- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
// 地理编码(地址关键字 ->经纬度 )
- (IBAction)geoCode {

    NSString *address = self.addressTV.text;

    // 容错处理
    if([address length] == 0)
    {
        return;
    }

    // 根据地址关键字, 进行地理编码
    [self.geoC geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

        /**
         *  CLPlacemark : 地标对象
         *  location : 对应的位置对象
         *  name : 地址全称
         *  locality : 城市
         *  按相关性进行排序
         */
        CLPlacemark *pl = [placemarks firstObject];

        if(error == nil)
        {
            NSLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);

            NSLog(@"%@", pl.name);
            self.addressTV.text = pl.name;
            self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
            self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
        }
    }];
}

// 反地理编码(把经纬度---> 详细地址)
- (IBAction)reverseGeoCode
{
    double latitude = [self.latitudeTF.text doubleValue];
    double longitude = [self.longitudeTF.text doubleValue];

    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];

        if(error == nil)
        {
            NSLog(@"%f----%f", pl.location.coordinate.latitude, pl.location.coordinate.longitude);

            NSLog(@"%@", pl.name);
            self.addressTV.text = pl.name;
            self.latitudeTF.text = @(pl.location.coordinate.latitude).stringValue;
            self.longitudeTF.text = @(pl.location.coordinate.longitude).stringValue;
        }
    }];
}
@end

原文地址:https://www.cnblogs.com/gchlcc/p/5845051.html