- 导入CoreLocation框架和对应的主头文件
#import <CoreLocation/CoreLocation.h>
- 创建CLGeocoder对象
_geoC = [[CLGeocoder alloc] init];
- 地理编码
- 根据地址进行地理编码
[self.geoC geocodeAddressString:@"科技八路" completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) { //返回结果可能有多个,因为一个地点有重名 // 包含区,街道等信息的地标对象 CLPlacemark *placemark = [placemarks firstObject]; // 城市名称 // NSString *city = placemark.locality; // 街道名称 // NSString *street = placemark.thoroughfare; // 全称 NSString *name = placemark.name; self.addressDetailTV.text = [NSString stringWithFormat:@"%@", name]; self.latitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude]; self.longtitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude]; }];
2. 根据地址和指定区域两个条件进行地理编码(更加精确)
//补充Region定义
[self.geoC geocodeAddressString:@"美寓华庭" inRegion:nil completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) { // 包含区,街道等信息的地标对象 CLPlacemark *placemark = [placemarks firstObject]; self.addressDetailTV.text = placemark.description; self.latitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude]; self.longtitudeTF.text = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude]; }];
- 反地理编码
// 创建CLLocation对象 CLLocation *location = [[CLLocation alloc] initWithLatitude:34.267 longitude:108.9; // 根据CLLocation对象进行反地理编码 [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * __nullable placemarks, NSError * __nullable error) { // 包含区,街道等信息的地标对象 CLPlacemark *placemark = [placemarks firstObject]; // 城市名称 // NSString *city = placemark.locality; // 街道名称 // NSString *street = placemark.thoroughfare; // 全称 NSString *name = placemark.name; self.addressDetailTV.text = [NSString stringWithFormat:@"%@", name]; }];