如何获取当前位置IOS设备

Posted

技术标签:

【中文标题】如何获取当前位置IOS设备【英文标题】:How to get current location IOS device 【发布时间】:2017-01-26 04:32:47 【问题描述】:

我一直在我的应用程序中使用 GMSMap。我想在我的 GMSMap 用户当前位置 lat long。我使用了很多方法,但没有得到当前位置。请帮助并指导如何获取我当前的位置。我已经阅读了很多教程并遵循但没有得到。

我有一个问题,我正在使用方法,我的项目中还有其他工作吗?我好累,请帮忙。

首先,我在我的项目中编写了以下显示方法,然后创建 IPA 并安装我的设备。但是不要获取当前位置的纬度经度。

请帮忙。谢谢你

首先

-(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];
         _adrs_lbl.text = Address;
         NSString *Area = [[NSString alloc]initWithString:placemark.locality];
        NSString *Country = [[NSString alloc]initWithString:placemark.country];
         _lat_lbl.text = Country;

         NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
         NSLog(@"%@",CountryArea);
         _long_lbl.text = CountryArea;

     
     else
     
         NSLog(@"Geocode failed with error %@", error);
         NSLog(@"\nCurrent Location Not Detected\n");
         //return;
         //CountryArea = NULL;

     

 ];
 

第二

- (void)viewDidLoad

[super viewDidLoad];

if ([CLLocationManager locationServicesEnabled]) 
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
 else 
    NSLog(@"Location services are not enabled");



- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

CLLocation *location = [locations lastObject];
self.latitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
self.longtitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
 

更新问题

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
currentLocation = [locations lastObject];
if (currentLocation != nil)
    NSLog(@"The latitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
    NSLog(@"The logitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);

//Current
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.latitude longitude: currentLocation.coordinate.longitude zoom:13];

self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.mapView.myLocationEnabled = YES;
self.mapView.delegate = self;
self.mapView.frame = viewDirection.bounds;
[viewDirection addSubview:self.mapView];

//    GMSMarker *marker = [[GMSMarker alloc] init];
//    marker.position = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
//    marker.title = @"Your Office Name";
//    marker.icon = [UIImage imageNamed:@"boss-icon.png"];
//    //OR
//    marker.icon = [GMSMarker markerImageWithColor:[UIColor blueColor]];
//    marker.snippet = @"Current Location";
//    marker.map = self.mapView;


GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1.position = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
marker1.icon = [GMSMarker markerImageWithColor:[UIColor redColor]];
marker1.title = @"my location";
marker1.snippet = @"City Name";
marker1.map = self.mapView;


GMSMarker *marker2 = [[GMSMarker alloc] init];
marker2.position = CLLocationCoordinate2DMake(22.6990,75.8671);
marker2.icon = [GMSMarker markerImageWithColor:[UIColor greenColor]];
marker2.title = @"Destination location";
marker2.snippet = @"City Name";
marker2.map = self.mapView;

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

NSString *destinationString = [NSString stringWithFormat:@"%f,%f",22.6990,75.8671];

NSString *str = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false",originString,destinationString];
NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) 
    if(data == nil) 
        return;
    else
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSArray* latestRoutes = [json objectForKey:@"routes"];
        NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
        _text.text = points;
        @try 
            // TODO: better parsing. Regular expression?
            NSArray *temp= [self decodePolyLine:[points mutableCopy]];
            GMSMutablePath *path = [GMSMutablePath path];
            for(int idx = 0; idx < [temp count]; idx++)
                CLLocation *location=[temp objectAtIndex:idx];
                [path addCoordinate:location.coordinate];
            
            // create the polyline based on the array of points.
            GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
            rectangle.strokeWidth=5.0;
            rectangle.strokeColor = [UIColor redColor];
            rectangle.map = self.mapView;

            [locationManager stopUpdatingLocation];
        
        @catch (NSException * e) 
            // TODO: show erro
        
    
];
[dataTask resume];

 [locationManager stopUpdatingLocation];

 

GMSMapView image

Check my PolyLine IMAGE

【问题讨论】:

兄弟,你是不是在 appdelagates 文件中放了一些方法来要求用户访问位置,并且你在 .plist 文件中放了权限吗? 请问如何解释? @HimanshuMoradiya 询问访问位置的方法。请用一些代码解释一下。 [self.locationManager requestWhenInUseAuthorization] [self.locationManager requestAlwaysAuthorization] 使用这个 是否调用了 didUpdateLocation 委托方法? 【参考方案1】:

我一步一步给你解决方案

第 1 步:

首先我们应该得到 Google Map SDK

将以下捆绑包拖到您的项目中(出现提示时,如果需要,请选择复制项目):

Subspecs/Base/Frameworks/GoogleMapsBase.framework
Subspecs/Maps/Frameworks/GoogleMaps.framework
Subspecs/Maps/Frameworks/GoogleMapsCore.framework

在您的项目中右键单击 GoogleMaps.framework,然后选择 Show In Finder。

将 GoogleMaps.bundle 从 Resources 文件夹拖到您的项目中。出现提示时,确保未选择将项目复制到目标组的文件夹中。

从项目导航器中选择您的项目,然后选择您的应用程序的目标。

打开 Build Phases 选项卡,在 Link Binary with Libraries 中,添加以下框架:

GoogleMapsBase.framework
GoogleMaps.framework
GoogleMapsCore.framework
GoogleMapsM4B.framework (Premium Plan customers only)
Accelerate.framework
CoreData.framework
CoreGraphics.framework
CoreLocation.framework
CoreText.framework
GLKit.framework
ImageIO.framework
libc++.tbd
libz.tbd
OpenGLES.framework
QuartzCore.framework
SystemConfiguration.framework
UIKit.framework

第 2 步:

Get the API key

第 3 步:

Add the below things in your Plist    

  App Transport Security Settings   Dictionary 
  Allow Arbitrary Loads             Boolean          YES


  <key>NSLocationWhenInUseUsageDescription</key>
  <string>RehabTask requires location services to work</string>

  <key>NSLocationAlwaysUsageDescription</key>
  <string>RehabTask requires location services to work</string>        

            OR

   Privacy - Location When In Use Usage Description   string    RehabTask requires location services to work
   Privacy - Location Always Usage Description        string    RehabTask requires location services to work

还需要添加

  <key>LSApplicationQueriesSchemes</key>
  <array>
     <string>googlechromes</string>
     <string>comgooglemaps</string>
  </array>

第 4 步:在 appDelegate 中添加以下代码

AppDelegate.m

@import GoogleMaps;
#import "AppDelegate.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

   [GMSServices provideAPIKey:@"AIzaSyCrCEb7qVkURIjq6jsfkPkwgN62sfj6Ff0"];
   return YES;

第 5 步:

ViewController.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <GoogleMaps/GoogleMaps.h>


@interface ViewController : UIViewController<CLLocationManagerDelegate,GMSMapViewDelegate>
    CLLocation *currentLocation;


@property (strong, nonatomic) IBOutlet UIView *viewDirection;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) GMSMapView *mapView;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize viewDirection,locationManager,
@synthesize mapView;

- (void)viewDidLoad 
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    locationManager = [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    locationManager.distanceFilter = 10;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if([CLLocationManager locationServicesEnabled] == NO)
        NSLog(@"Your location service is not enabled, So go to Settings > Location Services");
    
    else
        NSLog(@"Your location service is enabled");
    
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) 
       [locationManager requestWhenInUseAuthorization];
    
    [locationManager startUpdatingLocation];


#pragma mark - CLLocationManagerDelegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
    currentLocation = [locations lastObject];
    if (currentLocation != nil)
        NSLog(@"The latitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
        NSLog(@"The logitude value is - %@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
    
    //Current
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:currentLocation.coordinate.latitude longitude: currentLocation.coordinate.longitude zoom:13];

    self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    self.mapView.myLocationEnabled = YES;
    self.mapView.delegate = self;
    self.mapView.frame = viewDirection.bounds;
    [viewDirection addSubview:self.mapView];

    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    marker.title = @"Your Office Name";
    marker.icon = [UIImage imageNamed:@"boss-icon.png"];
                OR
    marker.icon = [GMSMarker markerImageWithColor:[UIColor blueColor]];
    marker.snippet = @"Current Location";
    marker.map = self.mapView;


    GMSMarker *marker1 = [[GMSMarker alloc] init];
    marker1.position = CLLocationCoordinate2DMake(22.7007,75.8759);
    marker1.icon = [GMSMarker markerImageWithColor:[UIColor redColor]];
    marker1.title = @"Place Name";
    marker1.snippet = @"City Name";
    marker1.map = self.mapView;


    GMSMarker *marker2 = [[GMSMarker alloc] init];
    marker2.position = CLLocationCoordinate2DMake(22.6990,75.8671);
    marker2.icon = [GMSMarker markerImageWithColor:[UIColor greenColor]];
    marker2.title = @"Place Name";
    marker2.snippet = @"City Name";
    marker2.map = self.mapView;

    NSString *originString = [NSString stringWithFormat:@"%f,%f",22.7007,75.8759];

    NSString *destinationString = [NSString stringWithFormat:@"%f,%f",22.6990,75.8671]; 

    NSString *str = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false",originString,destinationString];
    NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) 
        if(data == nil) 
            return;
        else
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
            NSArray* latestRoutes = [json objectForKey:@"routes"];
            NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
            @try 
                // TODO: better parsing. Regular expression?
                NSArray *temp= [self decodePolyLine:[points mutableCopy]];
                GMSMutablePath *path = [GMSMutablePath path];
                for(int idx = 0; idx < [temp count]; idx++)
                    CLLocation *location=[temp objectAtIndex:idx];
                    [path addCoordinate:location.coordinate];
                
                // create the polyline based on the array of points.
                GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
                rectangle.strokeWidth=5.0;
                rectangle.map = self.mapView;
                [locationManager stopUpdatingLocation];
            
            @catch (NSException * e) 
                // TODO: show erro
            
        
    ];
    [dataTask resume];
    
    [locationManager stopUpdatingLocation];


//I called below method in above temp(NSArray *temp = [self decodePolyLine:[points mutableCopy]]) for Drawing route between two or more places
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded 
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init] ;
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) 
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do 
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
         while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do 
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
         while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5] ;
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5] ;
        printf("[%f,", [latitude doubleValue]);
        printf("%f]", [longitude doubleValue]);
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
        [array addObject:loc];
    

    return array;


@end

快乐编码:-)

【讨论】:

无需添加。 我想在这段代码中再添加一行`rectangle.strokeColor` 在您的代码中应用相同的代码,并在您的代码中添加 UIView(viewDirection) 作为 outlet 属性。这就足够了。 你不需要添加rectangle.strokeColor。只要按照上面的步骤就可以得到输出。我在上面的API key中使用了key。有一切。不要添加任何额外的代码中的东西, 在方向 url 我也提到了你的 lat,long 值。【参考方案2】:

在 info.plist 中添加以下行

<key>NSLocationWhenInUseUsageDescription</key>
    <string>App required location because it is needed when .... </string>

还要检查您是否在代码中添加了以下行

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    
        [self.locationManager requestWhenInUseAuthorization];
    

【讨论】:

【参考方案3】:

正如其他人在他们的 cmets 中所建议的那样,您的 info.plist 中需要一到两个密钥,并且您需要询问用户是否允许使用 GPS。代码见此链接:

Checking location service permission on ios

下面的链接列出了你需要输入到你的 info.plist 的键和你需要的代码,但是代码是在 Swift 中的:

http://nshipster.com/core-location-in-ios-8/

【讨论】:

以上是关于如何获取当前位置IOS设备的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 中使用 GoogleCast frameWork 获取当前流位置

如何在 iOS 上获取当前位置? [复制]

如何以编程方式获取设备的当前地理位置

如何获取我的设备的当前位置 [重复]

如何获取android移动设备的当前位置经纬度?

iOS:如何获取设备当前语言设置?