簡體   English   中英

使用CLLocationmanager在Map iOS中顯示當前位置

[英]Show current location in map ios with CLLocationmanager

我試圖在地圖上顯示當前位置,但失敗了。 由於location為null,因此會給出錯誤。 在模擬器調試位置選項中應選擇哪個選項。 如果我嘗試不使用任何方法,則返回自定義的空位置nd,它給出預定坐標的位置。 我想獲得當前位置!

我認為您無法通過模擬器獲得當前位置。 您所要做的就是在“調試”->“位置”->“自定義位置”中提供當前位置的緯度和經度。 模擬器會將其用作當前位置。 另一種選擇是將GPX文件添加到您的項目方案中。編輯方案->選項->選中允許位置模擬。 將GPX文件添加到您的項目。 添加GPX文件

以上設置用於在模擬器中進行調試。即使沒有完成這些設置,它也將基於真實設備中的當前位置運行(適用於無故障代碼)。

首先創建對象

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

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
 if(IS_OS_8_OR_LATER)
 {
    [locationManager requestAlwaysAuthorization];
    [locationManager requestWhenInUseAuthorization];
 }
[locationManager startUpdatingLocation];

//Below two lines give you current location (lat-long).
Latitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.latitude];
NSLog(@"Lat====%@",Latitude);

Longitude = [NSString stringWithFormat:@"%f",locationManager.location.coordinate.longitude];
NSLog(@"Log====%@",Longitude);

您可以在AppDelegate.h添加它

@property (nonatomic, strong)  CLLocationManager *locationManager;

您可以使用它來獲取當前位置。 您可以在AppDelegate.m文件中添加此代碼

if ([CLLocationManager locationServicesEnabled]) {
        if (!_locationManager) {
            _locationManager = [[CLLocationManager alloc] init];
            _locationManager.delegate = self;
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            _locationManager.distanceFilter = 10.0;
            [self.locationManager startMonitoringSignificantLocationChanges];
        }
        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            [_locationManager requestAlwaysAuthorization];
        [_locationManager startUpdatingLocation];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM