Как узнать текущее местоположение устройства IOS
Я использую GMSMap в моем приложении. Я хочу, чтобы в моем пользователе GMSMap было указано текущее местоположение. Я использовал много методов, но не могу узнать текущее местоположение. Пожалуйста, помогите и укажите, как узнать мое текущее местоположение. Я прочитал много уроков и следую, но не понимаю.
У меня есть один вопрос, я использую методы, и любая другая работа будет в моем проекте? Я так устал, пожалуйста, помогите.
Сначала я написал в своем проекте методы show bellow, затем создал 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];
}
3 ответа
Я даю вам решение шаг за шагом
ШАГ 1:
Сначала мы должны получить SDK Google Map.
Перетащите следующие пакеты в ваш проект (при появлении запроса выберите Копировать элементы, если необходимо):
Subspecs/Base/Frameworks/GoogleMapsBase.framework
Subspecs/Maps/Frameworks/GoogleMaps.framework
Subspecs/Maps/Frameworks/GoogleMapsCore.framework
Щелкните правой кнопкой мыши GoogleMaps.framework в своем проекте и выберите "Показать в Finder".
Перетащите GoogleMaps.bundle из папки "Ресурсы" в свой проект. При появлении запроса убедитесь, что пункт Копировать объекты в папку целевой группы не выбран.
Выберите ваш проект в Навигаторе проектов и выберите цель вашего приложения.
Откройте вкладку "Фазы сборки" и в разделе "Связать двоичные файлы с библиотеками" добавьте следующие платформы:
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:
ШАГ 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
Удачного кодирования:-)
Добавьте следующие строки в ваш info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>App required location because it is needed when .... </string>
Также убедитесь, что вы добавили следующую строку в свой код
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
Как предлагают другие в их комментариях, вам нужен один или два ключа в вашем info.plist, и вы должны спросить пользователя о разрешении использовать GPS. Смотрите эту ссылку для кода:
Проверка разрешения службы определения местоположения на iOS
Ссылка ниже перечисляет ключи, которые вам нужно ввести в ваш info.plist, и код, который вам нужен, но код есть в Swift: