您的位置:首页 > 其它

获取当前经纬度并根据经纬度反编译城市地址

2014-09-13 10:25 761 查看
最近项目需要获取当前经纬度,然后根据经纬度反编译出所在城市,记录一下实现方法,主要是方便以后自己再次使用,写的比较粗糙:

要获取经纬度要使用framework的



在.h文件:引入

,执行代理方法CLLocationManagerDelegate,申明@property(nonatomic,retain)
CLLocationManager *locationManager;

.m文件:

//定位功能
-(void)localstart{

//
实例化一个位置管理器,用来获取经纬度

self.locationManager = [[CLLocationManager
alloc]
init];

self.locationManager.delegate =
self;

//
设置定位精度

// kCLLocationAccuracyNearestTenMeters:精度10米

// kCLLocationAccuracyHundredMeters:精度100


// kCLLocationAccuracyKilometer:精度1000


// kCLLocationAccuracyThreeKilometers:精度3000米

// kCLLocationAccuracyBest:设备使用电池供电时候最高的精度

// kCLLocationAccuracyBestForNavigation:导航情况下最高精度,一般要有外接电源时才能使用

self.locationManager.desiredAccuracy =
kCLLocationAccuracyBest;

// distanceFilter是距离过滤器,为了减少对定位装置的轮询次数,位置的改变不会每次都去通知委托,而是在移动了足够的距离时才通知委托程序

//
它的单位是米,这里设置为至少移动1000再通知委托处理更新;

self.locationManager.distanceFilter =
100.0f;

if ([CLLocationManager
locationServicesEnabled]) {

//
启动位置更新

//
开启位置更新需要与服务器进行轮询所以会比较耗电,在不需要时用stopUpdatingLocation方法关闭;

[self.locationManager
startUpdatingLocation];
}

else {

NSLog(@"请开启定位功能!");
}

}

//实现代理方法,在位置改变时调用

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation
*)newLocation fromLocation:(CLLocation *)oldLocation
{

//
获取经纬度

NSLog(@"纬度:%f",newLocation.coordinate.latitude);

NSLog(@"经度:%f",newLocation.coordinate.longitude);

NSString *weidu = [NSString
stringWithFormat:@"%f",newLocation.coordinate.latitude];

NSString *jingdu = [NSString
stringWithFormat:@"%f",newLocation.coordinate.longitude];

NSString * weidus = weidu;

NSString * jingdus = jingdu;

//根据经纬度反向编译城市信息

CLGeocoder *geocoder = [[CLGeocoder
alloc] init];
[geocoder
reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *array,
NSError *error)
{

if (array.count >
0)
{

for (CLPlacemark * placemark
in array) {

//当前城市名称

NSString *myCity = placemark.locality; // 比如:“西安市”
//把获取的城市名存放在NSUserDefaults中,在其它页面就可以直接使用,很方便

NSUserDefaults *localcity = [NSUserDefaults
standardUserDefaults];
[localcity
setObject:myCity forKey:@"city"];
}
}
}];

//
停止位置更新

[manager stopUpdatingLocation];
}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError
*)error
{

NSLog(@"error:%@",error);
}

至此,获取当前经纬度,反编译城市名称已经完成,很是简单
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: