簡體   English   中英

怎么把MKUserLocation轉換成CLLocation? -迅速

[英]How to convert MKUserLocation to CLLocation? - swift

我需要一種將MKUserLocation轉換為CLLocation的方法,以便可以使用swift中的distanceFromLocation方法找到用戶位置和另一個預定義的CLLocation之間的距離。

MKUserLocation具有屬性位置,該位置恰好是CLLocation類型。

參見https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKUserLocation_Class/index.html#//apple_ref/occ/instp/MKUserLocation/location

但是,您需要首先完成幾件事情。

  • 您需要征詢用戶使用其位置的權限 這包括調用CLLocationManager的requestWhenInUseAuthorization並檢查異步結果。
  • 將NSLocationWhenInInUseUsageDescription條目添加到您的信息中(在上面的鏈接中進行了描述),以告訴用戶您想對信息做什么
  • 您很可能需要異步獲取位置。 為此,您的視圖控制器需要實現MKMapViewDelegate,並且您將使用func mapView(mapView:MKMapView !, didUpdateUserLocation userLocation:MKUserLocation!)來獲取用戶位置。

我認為您是從mapView獲取MKUserLocation的嗎?

因此,您必須遵循以下步驟:

  1. 確保您具有用戶和系統權限以顯示用戶位置
  2. 一旦您的用戶位置顯示在mapView上,就將您的控制器設置為mapView委托。
  3. 實現方法- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation

     // Code - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { [userLocation.location distanceFromLocation:_yourOtherLocation]; } 

Xcode 6.4,適用於iOS 8.4,已啟用ARC

好的答案已經在這里發布了; 但是,沒有人給出具體的例子。 請記住以下幾點:

MKUserLocation類定義用於標識用戶當前位置的特定注釋類型。 您不直接創建此類的實例。 而是從您的應用程序中顯示的地圖視圖的userLocation屬性中檢索現有的MKUserLocation對象。

location屬性是只讀的!

var location: CLLocation! { get }

因此,使用此屬性可以直接使用distanceFromLocation :,但不要使用當前用戶的位置,因為它顯然會返回0米。 您很可能必須初始化一個新的CLLocation以進行測量。

func distanceFromLocation(_ location: CLLocation!) -> CLLocationDistance

希望這可以幫助! 干杯。

暫無
暫無

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

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