1.地理編碼:CLGeocoder對象傳入地名即可。
// 1.創建地理編碼對象
_geocoder = [[CLGeocoder alloc] init];
// 2.利用地理編碼對象編碼
// 根據傳入的地名獲取該地址對應的經緯度信息
[self.geocoder geocodeAddressString:@"北京" completionHandler:^(NSArray *placemarks, NSError *error) {
// placemarks地標數組, 地標數組中存放着地標, 每一個地標包含了該位置的經緯度以及城市/區域/國家代碼/郵編等等...
// 獲取數組中的第一個地標
CLPlacemark *placemark = [placemarks firstObject];
NSString *latitude = [NSString stringWithFormat:@"%f", placemark.location.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", placemark.location.coordinate.longitude];
//address存的都是地址信息,用一個string拼接起來就是完整的地址
NSArray *address = placemark.addressDictionary[@"FormattedAddressLines"];
NSMutableString *strM = [NSMutableString string];
for (NSString *str in address) {
[strM appendString:str];
}
2.反地理編碼:
// 2.根據用戶輸入的經緯度創建CLLocation對象
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude doubleValue] longitude:[longtitude doubleValue]];
// 3.根據CLLocation對象獲取對應的地標信息
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
NSLog(@"%@ %@ %f %f", placemark.name, placemark.addressDictionary, placemark.location.coordinate.latitude, placemark.location.coordinate.longitude);
self.reverseDetailAddressLabel.text = placemark.locality;
}
}];