簡體   English   中英

MKMapView或CLLocationManger-確定用戶的當前位置

[英]MKMapView or CLLocationManger - to determine user's current location

有兩個類可幫助您進行地圖繪制和確定用戶位置MKMapViewCLLocationManager

MKMapView有一個委托“ didUpdateUserLocation ”,它告訴用戶當前的位置。 同時, CLLocationManger有一個委托“ didUpdateToLocation ”,它也做同樣的事情。

我的問題是何時使用MKMapViewCLLocationManager 我可以從MKMapView獲取設備的當前位置,然后為什么以及何時應該使用CLLocationManager 我試圖得到它,但我仍然不確定。

我認為您將MKMapView屬性showsUserLocationCLLocationManager混淆了。

為方便起見,MKMapView允許您簡單地啟用一個屬性以在地圖UI上向用戶顯示當前位置。 如果只需要向用戶顯示他們在地圖上的位置,這將非常方便。

但是,顯然還有許多其他用例,僅在地圖上顯示位置是不夠的,這就是CLLocationManager用武之地。

例如,考慮一個跑步/訓練應用程序,其中需要記錄用戶位置才能計算跑步距離,甚至考慮我自己的一個應用程序中的示例,在該應用程序中我需要查找用戶位置(經/緯度)來計算距離實時訪問各個火車站,以識別最接近用戶的位置。 在這些示例中,不需要MapView,因此使用LocationManager是正確的選擇。

任何時候您需要以編程方式與用戶位置進行交互,並且基本上不需要地圖UI!

我更喜歡使用MKMapView內部使用的CLLocationManager,因此,如果不需要使用地圖,只需使用位置管理器中的以下代碼。

locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];

只是不要忘記將locationManager實例存儲在類中的某個位置,並且您可以像這樣實現委托。

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Error detecting location %@", error);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation* location = (CLLocation*)locations.lastObject;
    NSLog(@"Longitude: %f, Latitude: %f", location.coordinate.longitude, location.coordinate.latitude);
}

編輯

您可以使用Apple的地理編碼器根據用戶的位置獲取用戶的地址

// Use Apple's Geocoder to figure the name of the place
    CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler: ^(NSArray* placemarks, NSError* error) {
        if (error != nil) {
            NSLog(@"Error in geo coder: %@", error);
        }
        else {
            if (placemarks.count == 0) {
                NSLog(@"The address couldn't be found");
            }
            else {
                // Get nearby address
                CLPlacemark* placemark = placemarks[0];

                // Get the string address and store it
                NSString* locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
                location.name = locatedAt;

                NSLog(@"The address is: %@", locatedAt);
            }
        }
    }];

暫無
暫無

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

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