如何在iOS中使用CLLocationManager获取当前位置

7
我可以使用经纬度找到当前位置,但我也想根据邮政编码找到当前位置。
以下是我目前的代码: .h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>


@interface ViewController : UIViewController<CLLocationManagerDelegate>

{

CLLocationManager *locationManager;
 CLLocation *currentLocation;

    IBOutlet UILabel *label1;
    IBOutlet UILabel *lable2;

}
@property (weak, nonatomic) IBOutlet MKMapView *myMapview;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *lable1;
@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad

{

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc]init];



    locationManager.delegate = self;


    locationManager.distanceFilter = kCLDistanceFilterNone;


    locationManager.desiredAccuracy = kCLLocationAccuracyBest;


    [locationManager startUpdatingLocation];


    _myMapview.showsUserLocation = YES;

    [self->locationManager startUpdatingLocation];



    CLLocation *location = [locationManager location];


    CLLocationCoordinate2D coordinate = [location coordinate];


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

    //NSLog(@”dLatitude : %@”, latitude);
    //NSLog(@”dLongitude : %@”,longitude);
    NSLog(@"MY HOME :%@", latitude);
    NSLog(@"MY HOME: %@ ", longitude);

}

#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];

    [self->locationManager stopUpdatingLocation];




    NSLog(@"my latitude :%f",currentLocation.coordinate.latitude);

    NSLog(@"my longitude :%f",currentLocation.coordinate.longitude);
    label1.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];


    NSLog(@"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation
                   completionHandler:^(NSArray *placemarks, NSError *error)
     {
                       if (error)
                       {
                           NSLog(@"Geocode failed with error: %@", error);
                           return;
                       }

NSLog(@"Monday");
                       CLPlacemark *placemark = [placemarks objectAtIndex:0];
                       NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);

                   }];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

    label1.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你的措辞有些令人困惑。你说你想根据邮政编码找到用户的“当前”位置。然而,如果你指定一个任意的邮政编码,那么你并不想得到用户的当前位置,而是想计算该邮政编码的位置。这两件事是不同的。 - Duncan C
4个回答

22

步骤1:.h文件中导入MobileCoreServices框架

#import <MobileCoreServices/MobileCoreServices.h>

步骤2: 添加委托CLLocationManagerDelegate

@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

步骤 3:将此代码添加到类文件中

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self CurrentLocationIdentifier]; // call this method
}

步骤4:获取位置的方法

//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
    //---- For getting current gps location
    locationManager = [CLLocationManager new];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    //------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (!(error))
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSLog(@"\nCurrent Location Detected\n");
             NSLog(@"placemark %@",placemark);
             NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
             NSString *Address = [[NSString alloc]initWithString:locatedAt];
             NSString *Area = [[NSString alloc]initWithString:placemark.locality];
             NSString *Country = [[NSString alloc]initWithString:placemark.country];
             NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
             NSLog(@"%@",CountryArea);
         }
         else
         {
             NSLog(@"Geocode failed with error %@", error);
             NSLog(@"\nCurrent Location Not Detected\n");
             //return;
             CountryArea = NULL;
         }
         /*---- For more results 
         placemark.region);
         placemark.country);
         placemark.locality); 
         placemark.name);
         placemark.ocean);
         placemark.postalCode);
         placemark.subLocality);
         placemark.location);
          ------*/
     }];
}

5
你的帖子很好地解释了如何确定用户当前位置的邮政编码。但是,用户正在寻找相反的信息——如何根据邮政编码找到位置。这需要使用正向地理编码而不是逆向地理编码。 - Duncan C
@SVM-RAjESH 谢谢你的回答,我会尝试。 - user3239699
@Duncan C,使用邮政编码获取某个位置是否可能? - user3239699
1
#import <MobileCoreServices/MobileCoreServices.h> 是用来做什么的?对于 CLLocationManager,你需要使用 CLLocation 框架。在 reverseGeocode 函数中,你应该枚举每个 placemark 对象,而不仅仅是第一个对象。 - Pawan Rai
1
@PavanAlapati,你想使用CLGeocoder方法geocodeAddressString。看看能否在我不给你代码的情况下自己解决它。 - Duncan C
显示剩余5条评论

6

这里是一个使用块获取用户当前位置的代码

1) #import <CoreLocation/CoreLocation.h>

2) <CLLocationManagerDelegate>

3) 在 .h 文件中

//Location
typedef void(^locationBlock)();

//Location
-(void)GetCurrentLocation_WithBlock:(void(^)())block;

@property (nonatomic, strong) locationBlock _locationBlock;
@property (nonatomic,copy)CLLocationManager *locationManager;
@property (nonatomic)CLLocationCoordinate2D coordinate;
@property (nonatomic,strong) NSString *current_Lat;
@property (nonatomic,strong) NSString *current_Long;

4)在.m文件中

#pragma mark - CLLocationManager
-(void)GetCurrentLocation_WithBlock:(void(^)())block {
    self._locationBlock = block;
    _locationManager = [[CLLocationManager alloc] init];
    [_locationManager setDelegate:self];
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    if (IS_OS_8_OR_LATER) {
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
            [_locationManager requestAlwaysAuthorization];
        }
    }
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLoc=[locations objectAtIndex:0];
    _coordinate=currentLoc.coordinate;
    _current_Lat = [NSString stringWithFormat:@"%f",currentLoc.coordinate.latitude];
    _current_Long = [NSString stringWithFormat:@"%f",currentLoc.coordinate.longitude];
    NSLog(@"here lat %@ and here long %@",_current_Lat,_current_Long);
    self._locationBlock();
    [_locationManager stopUpdatingLocation];
    _locationManager = nil;
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
}

5) 调用函数

- (void)viewDidLoad {
    [super viewDidLoad];
    [self GetCurrentLocation_WithBlock:^{
        NSLog(@"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]);
    }];
}

6) 并将以下内容添加到plist文件中

在Info.plist文件中需要添加下面的一个或两个键。

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

0

如果你在第一次启动时没有请求位置权限,那么你无法获取当前位置。

iOS8 通过 LocationsServices 进行了重大的 API 更改。

假设 [CLLocationManager locationServicesEnabled] 返回 YES,

在 iOS 应用程序的首次启动中[无论是 iOS7 还是 iOS8] - locationMangers(CLLocationManager)


0

您可以调用Google APIs Maps服务,通过邮政编码获取位置:

只需在address={您的邮政编码}中输入您的邮政编码即可。


我的代码只在控制台中显示,而不在模拟器的地图中显示。 - user3239699
当然,你必须自己在地图上显示该位置。 - Ajay
经度和纬度数据为Double类型,但我不知道如何将NSDictionsary的值传递到Double变量中。 - user3239699
首先,您需要解析整个JSON响应并从中获取值。 - Ajay
如果你理解了我的代码,那么请找到在地图上显示第7个位置的解决方案。 - user3239699
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接