I need a way to convert MKUserLocation to CLLocation so that I can find the distance between the user location and another predefined CLLocation using the distanceFromLocation method in swift.
3 Answers
MKUserLocation has property location, which happens to be of type CLLocation.
However, there are couple of things that you need to put in place first.
- You need to ask the user for permission to use their location. That includes calling CLLocationManager's requestWhenInUseAuthorization and checking for the asynchronous result.
- Adding NSLocationWhenInUseUsageDescription entry to your info (described in the link above) to tell the user what you want to do with the information
- You will most likely need to get the location asynchronously. In order to do that, your view controller needs to implement MKMapViewDelegate and you will use func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) to get the user location.

- 11,515
- 5
- 35
- 28
-
whenever i use this property, it appears to be nil and the user location is already shown. – dhruvm Feb 22 '15 at 19:59
-
Ok, I expanded the answer. – MirekE Feb 22 '15 at 21:22
I think you're getting your MKUserLocation from a mapView right ?
So you'll have to follow these steps :
- ensure that you have the user & system permission to display user location
- once you have the user location displayed on your mapView, set your controller as the mapView delegate.
implement the method :
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
// Code - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { [userLocation.location distanceFromLocation:_yourOtherLocation]; }

- 6,674
- 3
- 41
- 46
Xcode 6.4, for iOS 8.4, ARC enabled
Good answers already posted here; however, none give specific examples in swift. Here are a few things to keep in mind:
The MKUserLocation class defines a specific type of annotation that identifies the user’s current location. You do not create instances of this class directly. Instead, you retrieve an existing MKUserLocation object from the userLocation property of the map view displayed in your app.
The location property is read-only!
var location: CLLocation! { get }
So using this property it is possible to use distanceFromLocation: directly, but don't use the current user's location, because it will obviously return 0 meters. You will most likely have to initialize a new CLLocation to measure to.
func distanceFromLocation(_ location: CLLocation!) -> CLLocationDistance
Hope this helps! Cheers.

- 3,394
- 2
- 24
- 55