Search code examples
swiftcore-locationcllocationcoordinate2dcllocationdistance

Finding the distance between current location and another location


I'm not a programmer but have been playing around with a side project for fun. I'm using Xcode 10, Swift 5. I've pieced together a handful of things through youtube and SO but I've searched and experimented with this for three days and I'm running into dead ends here.

I am trying to determine the distance between a user's current location and a preset point (in this case the airport). I am able to find the distance between two hard-coded locations. I am also able to find and print the user's current location in the console. But when I try to combine those I am struggling, most often getting the error

'Value of type 'CLLocationCoordinate2D' has no member 'distance''

The code that working is and gives me the distance in meters I would like is:

lazy var phx = CLLocation(latitude: 33.409016, longitude: -111.805576)
lazy var distanceFromPhoenixToVegas = las.distance(from: phx)

And this will print out the current location coordinates:

func printCoordinates(){
     if let location = locationManager.location?.coordinate {
            print (location)
     }
}

If any one could offer guidance I would appreciate it.

Side note, there are a lot of similar questions on Stack Overflow. There are questions about getting a user's current location, and questions about getting distances between two points. I believe this is essentially what I am asking, but it was only answered by the original poster, and the answer seems not exactly correct to me. iOS & Swift: display distance from current location?


Solution

  • phx is of type CLLocation You only need locationManager.location

    if let location = locationManager.location {
       print(phx.distance(from: location))
    }
     
    

    Note that phx is CLLocation, not CLLocationCoordinate2D.