您的位置:首页 > 移动开发 > IOS开发

从零开始系列之iOS地图获取当前城市

2015-06-02 16:50 435 查看


发现之前的地图获取当前地理位置信息在Deprecated in iOS 5.0。已经被苹果弃之不用了。推荐

使用CLGeocoder来替代。发现非常简单,比之前写的方法简单了不少。

地图的前提是你导入了MapKit这个库
#import <MapKit/MKMapView.h>


先声明一个全局的CLLocationManager对象。
CLLocationManager *_currentLoaction;


之后开启定位功能。
_currentLoaction = [[CLLocationManager alloc] init];
_currentLoaction.delegate = self;
[_currentLoaction startUpdatingLocation];

定位结束之后更新当前的地址经纬度等信息。

#pragma mark - Location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"locError:%@", error);

}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[_currentLoaction stopUpdatingLocation];

NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
NSLog(@"Lat: %@  Lng: %@", strLat, strLng);

[_geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
_placeMark = [placemarks objectAtIndex:0];
_locationLabel.text = _placeMark.administrativeArea;
ITTDINFO(@"%@",_locationLabel.text);
// we have received our current location, so enable the "Get Current Address" button
}];
}
解释

_geocoder 这个是我先要声明的CLGeocoder。使用之前要alloc,才能使用。

我刚开始犯了一个低级错误,没有在viewDidLoad方法中_geocoder = [[CLGeocoder alloc] init];导致一直nil无法出现block的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息