iphone中GPS精确定位及反向获取地址信息
2013-05-30 12:02 三戒1993 阅读(196) 评论(0) 编辑 收藏 举报刚开始习惯性用CoreLocation.framework框架中的CLLocationManagerDelegate,获取当前的经纬度,再用经纬度反向解析出当前位置。代码如下:
.h文件
#import<UIKit/UIKit.h>
#import<CoreLocation/CoreLocation.h>
#import<MapKit/MapKit.h>
@interface FirstViewController :UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>{
CLLocationManager *lm;
}
@property (retain,nonatomic) IBOutletUILabel *locationLabel;
@property (retain,nonatomic) IBOutletMKMapView *map;
.m文件
#import"FirstViewController.h"
@implementation FirstViewController;
@synthesize locationLabel;
@synthesize map;
- (void)viewDidLoad
{
[superviewDidLoad];
lm = [[CLLocationManageralloc]init];
lm.delegate =self;
lm.desiredAccuracy =kCLLocationAccuracyBest;//设置最高精度
lm.distanceFilter =kCLDistanceFilterNone;
[lmstartUpdatingHeading];//方向
[lmstartUpdatingLocation];//位置
map.delegate =self;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"定位出错");
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
// //解析并获取当前坐标对应得地址信息
if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 5.0) {
// NSLog(@"iphone :%f",[[[UIDevice currentDevice] systemVersion] floatValue]);
CLGeocoder *clGeoCoder = [[CLGeocoderalloc] init];
CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error)
{
for (CLPlacemark * placeMarkin placemarks){
self.locationLabel.text = placeMark.name;
}
};
[clGeoCoder reverseGeocodeLocation:newLocationcompletionHandler:handle];
[clGeoCoder release];
[manager stopUpdatingLocation];
}else {
//[self startedReverseGeoderWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
NSLog(@"iphone :%f",[[[UIDevicecurrentDevice] systemVersion]floatValue]);
}
}
(void)viewDidLoad
{
[superviewDidLoad];
[mapsetHidden:YES];
map.showsUserLocation =YES;
map.delegate = self;
}
因为要调用MKMapViewDelegate委托里的方法,需实例化一个mapview,如果在实际项目过程中不想显示地图,可以设置位Hidden。
将map.showsUserLocation设置为YES,才能开启定位获取到用户当前地理位置的信息。获取后再设置为NO即可停止定位。
注意下面这个方法是MKMapViewDelegate委托里的方法,而不是CLLocationManagerDelegate委托里的方法。反向解析的代码基本一致。
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
//CLLocationCoordinate2D coords = userLocation.location.coordinate;
CLLocation * newLocation = userLocation.location;
// NSLog(@"2::::::%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
// //解析并获取当前坐标对应得地址信息
if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 5.0) {
CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
CLGeocodeCompletionHandler handle = ^(NSArray *placemarks,NSError *error)
{
for (CLPlacemark * placeMark in placemarks)
{
self.locationLabel.text = placeMark.name;
map.showsUserLocation = NO;
}
};
[clGeoCoderreverseGeocodeLocation:newLocation completionHandler:handle];
[clGeoCoderrelease];
}
}