通过一个有意义的地址得到一组经纬度数据
你想通过一个地理名称得到一组经纬度数据
通过 GLGeocoder 这个类的 geocodeAddressString:completionHandler 这个方法来实现
反向地理编码是通过一组经纬度数据的到一个实在的地理位置名称。同样我们可以使用 地理编码通过一个地理名称得到一组经纬度数据。地理编码和反向地理编码的功能都被封装 在 Core Location 框架中的 CLGeocoder 类中。
我们通过给 CLGeocoder 类的 geocodeAddressString:completionHandler 这个方法传递一 个 String 类型的地理位置名称来进行地理编码。这个方法的 completionHandler 参数接收一 个 block 对象,这个 block 对象不返回任何内容,但是接收两个参数:
1、一个地标数组(NSArray 类型),这将被设置为与地址相匹配的位置。
2、一个 error(NSError 类型),如果地理编码失败了,将会设置一个错误码。
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController
@property (nonatomic,strong) CLGeocoder *myGeocoder;
@end
---------------
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void) didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
[super viewDidLoad];;
NSString *oreillyAddress = @"1005 Gravenstein Highway North, Sebastopol, CA 95472, USA";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks,NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(@"Found %lu placemark(s)",(unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
NSLog(@"Longitude = %f",firstPlacemark.location.coordinate.longitude);
NSLog(@"Latitude = %f",firstPlacemark.location.coordinate.latitude);
}
else if ([placemarks count] == 0 && error == nil)
{
NSLog(@"Found no placemarks");
}
else if(error != nil)
{
NSLog(@"An error occurred = %@",error);
}
}];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
@end
评论